java reflection (a)

Reflection :
is to get information of the object through the object behind; [class constructor present, common methods, attributes, etc.]
Class Class : -
Interface: the Serializable, the GenericDeclaration, the Type, AnnotatedElement
- reflection operation is completed core classes are Class class;
- each class has its own unique class object, which is generated when the class is loaded by the JVM, users can only get, can not create
[three ways to obtain the class object]
1. object provided by getClass () method ( this method will produce an instance of the object)
2. class .class
3. class provided by forName () method
public static class <?> forName (String className) throws ClassNotFoundException

public class TestDemo {
    public static void main(String[] args) throws ClassNotFoundException {
        Date date = new Date();
        //1.Object类的getClass方法,此方法要先获得类的对象
        System.out.println(date.getClass());
        //类.class方法
        System.out.println(Date.class);
        //Class的forName方法
        System.out.println(Class.forName("java.util.Date"));
    }
}

After getting a Class object class

[Example 1 by reflection object newInstance ()}
public T newInstance () throws InstantiationException, IllegalAccessException

public class TestDemo {
    public static void main(String[] args) throws IllegalAccessException, InstantiationException {
      Object cls =  Date.class;
      //拿到Class对象后,调用newInstance()方法
        System.out.println(((Class) cls).newInstance());
    }
}

2. [obtained package name, parent, the parent interface information]
1. Obtain getPackage class package name provided -Class () method
2. The obtained -Class parent class provides getSuperclass () Method
3. The parent obtaining interface information -Class the getInterfaces class provides ()


interface Ilipstick{
}
interface Fruit{
}
class Person{
}
class Student extends Person{

}
class SuperMarker implements Ilipstick,Fruit{
}
public class TestJ{
    public static void main(String[] args) {
    //获得Class对象
        Class<?> cls = Student.class;
        Class<?> cl = SuperMarker.class;
        //获得包信息
        Package p = cls.getPackage();
        System.out.println(p);
        //获得父类信息
        Class<?> c = cls.getSuperclass();
        System.out.println(c.getName());
        //获得父接口信息
        Class[] g = cl.getInterfaces();
        for (Class<?> class1 :g){
            System.out.println(class1.getName());
        }
    }
}

[3. obtain property, constructor, method] ordinary
Person class, Student categories:

class Person{
    public String name;
    public int age;
}
class Student {
    public String School;
    public String skill;
    private int bob;
    protected String sod;
    public  Student(){}
    public Student(String name){}
    public Student(String name ,int age){}

    public void setSchool(String school) {
        School = school;
    }
    public void setSkill(String skill) {
        this.skill = skill;
    }
    public String getSchool() {
        return School;
    }
    public String getSkill() {
        return skill;
    }
}

1. Get Attribute
(1) (parent class) - made all the attributes in the class: public Field [] getFields () throws SecurityException

(2) (in this class) - made all class attributes:. Public Field [] getDeclaredFields () throws SecurityException

public class TestJ{
    public static void main(String[] args) throws NoSuchFieldException, ClassNotFoundException {
         Class<?> cls = Class.forName("Student");
        {
            //获得所有的"公有字段",也可取得父类的属性
            Field[] fie1 = ((Class) cls).getFields();
            for (Field fiel : fie1) {
                System.out.println(fiel);
            }
            System.out.println("-----------------------------");
            //取得所有的字段,包含被封装的
            Field[] fie2 = ((Class) cls).getDeclaredFields();
            for (Field field : fie2) {
                System.out.println(field);
            }
        }
    }
}

2. Obtain -Class class constructor reflected by the object when the class is instantiated, can only call the constructor with no arguments class
- <?> The Constructor public [] getConstructors () throws a SecurityException
- <?> The Constructor public getConstructor (Class ... The parameterTypes )
throws NoSuchMethodException, SecurityException

public class TestJ{
    public static void main(String[] args) throws NoSuchFieldException, ClassNotFoundException {
         Class<?> cls = Class.forName("Student");
         //调用类中的全部构造方法
         Constructor<?>[] cons = cls.getConstructors();
         for(Constructor<?> con :cons){
             System.out.println(con);
         }
         System.out.println("------------------");
         //获得指定参数的构造方法
        System.out.println(cls.getConstructor(String.class));
      }
  }

3.取得普通方法
-public Method[] getMethods() throws SecurityException
-public Method getMethod(String name, Class<?>… parameterTypes)
-调用public Object invoke(Object obj, Object… args)throws IllegalAccessException,
IllegalArgumentException,InvocationTargetException

public class TestJ{
    public static void main(String[] args) throws NoSuchFieldException, ClassNotFoundException {
         Class<?> cls = Class.forName("Student");
         //调用类中的全部普通方法
         Method[] methods = cls.getMethods();
         for(Method method : methods){
             System.out.println(method);
         }
          System.out.println("------------------");
        //获得指定普通方法
        System.out.println(cls.getMethod("setSkill", String.class));
        System.out.println("------------------");
        //调用invoke()方法
        //获得setSchool这个方法的实例化对象,设置方法名与参数
        Method setMethod = cls.getMethod("setSchool", String.class);
        //传入参数
        setMethod.invoke(obj,"清华");
        Method getMethod = cls.getMethod("getSchool");
        Object result = getMethod.invoke(obj);
        System.out.println(result);
    }
}

Guess you like

Origin blog.csdn.net/weixin_43573534/article/details/89811612