&& && reflection enumeration class notes

What is an enumeration class?

Enumeration class is a special object class defines a fixed optimization.

In other words, in the example of the need for a class or a plurality of relatively fixed and when using enumeration class. (Scalable enumeration class)


Instances of classes are relatively fixed date, some of the same number, etc. objective.

enum WorkDay
{
    MONDAY, THUEDAY, WEDNESDAY , THURSDAY , FRIDAY;
}


public class Main {

    public static void main(String[] args) {
        System.out.println("Hello World!");

        WorkDay workDay;

        workDay=WorkDay.MONDAY;   //WorkDay实例化的workday值限定在周一到周五之间

//      workDay=3;     //编译报错

        WorkDay []workDays = WorkDay.values();  //返回枚举类型的对象数组

        for(int i =0;i<workDays.length;i++)
        {
            System.out.println(workDays[i]);
        }



        /**
         * 单例模式是枚举类的特例,单例模式的要求是一个类只能由一个实例对象。
         * 枚举类的使用是定义类时固定其一个或多个对象
         *
         * 枚举类的特点:
         *  - 类型安全(枚举类的定义就是固定的)
         *  - 枚举类的对象自动添加private static final
         *  - 某种程度的解耦,枚举类可以加一组常量或者对象抽离出主程序,减小类之间的耦合性。在枚举类模板的扩展上也更加容易
         */

    }
}

annotation

Annotation is actually a code of special markers , these markers can be compiled, class loading, it is read runtime and executes the corresponding processing.

Notes is essentially an interface and a set of key-value pairs to achieve a certain behavior through reflection and agents.


[Frame + reflector + = annotation design pattern. ]

/**
 * @author shkstart
 * @version 1.0
 *
 */
public class Main {
    /**
     * 程序的主方法,程序的入口
     * @param args String[] 命令行参数
     */

    @SuppressWarnings("unused")  //抑制编译器警告
    int a = 10;

    @Deprecated     //用于表示所修饰的元素(类, 方法等)已过时。通常是因为所修饰的结构危险或存在更好的选择
    public void print(){
        System.out.println("过时的方法");
    }
    @Override       //限定重写父类方法, 该注解只能用于方法
    public String toString() {
        return "重写的toString方法()"; }
    public static void main(String[] args) {
    }
    /**
     * 求圆面积的方法
     * @param radius double 半径值
     * @return double 圆的面积
     */
    public static double getArea(double radius){
        return Math.PI * radius * radius; }
}

reflection

What is reflection?

Reflection Reflection API allows a program to make any type of internal information by means of operation, and internal properties and methods of any object can be directly operated. (Highest authority)



Object class

package java.lang;

public class Object {

   private static native void registerNatives();
    static {
        registerNatives();
    }


    public final native Class<?> getClass();

    public native int hashCode();

    public boolean equals(Object obj) {
        return (this == obj);
    }

    protected native Object clone() throws CloneNotSupportedException;


    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }


    public final native void notify();


    public final native void notifyAll();


    public final native void wait(long timeout) throws InterruptedException;

 
    public final void wait(long timeout, int nanos) throws InterruptedException {
        if (timeout < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (nanos < 0 || nanos > 999999) {
            throw new IllegalArgumentException(
                                "nanosecond timeout value out of range");
        }

        if (nanos > 0) {
            timeout++;
        }

        wait(timeout);
    }

    
 
    public final void wait() throws InterruptedException {
        wait(0);
    }


    protected void finalize() throws Throwable { }
}

One such method which has

public final native Class<?> getClass();


Get instance of class Class

  • Specifically, if known classes, properties acquired by the class, which is the most secure method, program highest performance

  • Known examples of a class, calling the instance getClass () method to get Class object

  • Known full class name of a class, and the class in the class path, may be obtained by the static method forName Class class (), may throw ClassNotFoundException

    Class test  = String.class;
    
    
    Class test01 = "Hello World!".getClass();
    
    
    Class test02 = Class.forName("java.lang.String");  //抛异常

All classes inherit Object, so String.class returns an instance of the class.

Class forName class has a method, the return value is Class:

1566714256892

Access to information classes, properties, and method calls the class

package test;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

class Work {
    private String name;
    private Integer age;
    private String gender;
    private String job;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    @Override
    public String toString() {
        return "Work{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                ", job='" + job + '\'' +
                '}';
    }
}


public class ReflectWork
{

    public static void main(String[] args) throws IllegalAccessException, InstantiationException, ClassNotFoundException {


        Class classWork = Class.forName("test.Work");


        System.out.println(" ///获取所有方法信息"
        );


        Method []methods= classWork.getDeclaredMethods();

        for (Method m:methods) {
            System.out.println(m.toString());

        }

        System.out.println("  //获取所有成员属性信息");

        Field[] field=classWork.getDeclaredFields();
        for(Field f:field){
            System.out.println(f.toString());

            f.setAccessible(true);  //取消类的私有属性的访问权限控制

            System.out.println(f.getName().toString());
        }


        System.out.println("//通过反射初始化");
        Work reflectWork = (Work) classWork.newInstance();
        reflectWork.setAge(22);
        reflectWork.setJob("Dev");
        Work work = reflectWork;

        System.out.println(work);




    }
}

1566716123925

Guess you like

Origin www.cnblogs.com/noneplus/p/11407922.html