Reflection mechanism in java
effect:
- JAVA reflection mechanism is in the running state, for any class, all the attributes and methods of this class can be known;
- For any object, any method and attribute can be called;
- The function of dynamically obtaining information and dynamically calling object methods is called the reflection mechanism of java language
Specific operation:
Examples:
package test;
public class Student {
public Student(){
}
public Student(int num,String name){
}
private int num;
public String name;
protected String address;
}
Use reflection to get the class:
-
To get the object of the class, use the object.getclass();
Student st=new Student(); st.getclass();
-
Class name.class;
Student.class;
-
Class.forName("package name, class name");
Class.forName("test、Student");
Use reflection to obtain constructors, attributes and methods in a class:
- Get the constructor in the class
//测试类中的代码
Class c=Student.class;
//getConstructors只能获得公共构造器//getDeclaredConstructors获得所有构造器
//constructor是获取构造器时所用
Constructor[] cs= c.getConstructors;
for (Constructor constructor : cs) {
Student st=(Student)constructor.newInstance();
System.out.println(st);
}
-
Get the attributes in the class
public class Test{ public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { //获得反射,获取属性的关键代码 Class c=Student.class; Field[] fs= c.getDeclaredFields(); for (Field field : fs) { System.out.println(field); } //输出的结果为 /* private int com.qm.test.Student.num * public java.lang.String com.qm.test.Student.name * protected java.lang.String com.qm.test.Student.address */ } }
-
Get methods in the class
public class Test{ public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { //获取方法的关键代码 Class c=Student.class; Method[] ms=c.getMethods(); for (Method method : ms) { System.out.println(method); } //此段代码将会输出Student类中继承了Object类的一些方法 } }
*Disclaimer: This blog post is a study note, refer to the rookie tutorial and other network resources, if there is any infringement or error, please let us know by private message! *