反射是通过.class文件获取一个类的信息 JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制
package edu.uestc.LearnningTest.Reflect;
import lombok.Data;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@Data
class Stu{
public String address ;
private String name;
private int age;
public Stu(){
}
public Stu(String name,int age){
this.name = name;
this.age = age;
}
public static void main(String[] args) {
System.out.println("hello");
}
}
public class Learining1 {
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ClassNotFoundException, NoSuchFieldException, InstantiationException {
Stu stu1 = new Stu("zs",10);
Class one =stu1.getClass();
System.out.println(one.getSimpleName());
Class two = Stu.class;
System.out.println(one == two);
Class three = Class.forName("edu.uestc.LearnningTest.Reflect.Stu");
System.out.println(one == three);
Field[] AllField ;
AllField = three.getDeclaredFields();
for(Field s : AllField){
System.out.println(s.getName());
}
Field[] PrivateField;
PrivateField = three.getFields();
for(Field s : PrivateField)
System.out.println(s.getName());
Field f = three.getField("address");
try{
Object ob = three.getConstructor().newInstance();
f.set(ob,"10086");
Stu three1 = (Stu) ob;
System.out.println(three1.getAddress());
} catch (InstantiationException e) {
e.printStackTrace();
}
Field f1 = three.getDeclaredField("name");
try{
Object obj = three.getConstructor().newInstance();
f1.setAccessible(true);
f1.set(obj,"w5");
Stu three2 = (Stu) obj;
System.out.println(three2.getName());
} catch (InstantiationException e) {
e.printStackTrace();
}
Method[] m = three.getMethods();
for(Method m1 : m){
System.out.println(m1);
}
System.out.println("****************************");
Method[] m1 = three.getDeclaredMethods();
for(Method m2 : m1){
System.out.println(m2);
}
Method m2 = three.getMethod("getAge",null);
Method m3 = three.getDeclaredMethod("setName",String.class);
try{
Object obj = three.getConstructor().newInstance();
m2.invoke(obj,null);
m3.invoke(obj,"qiuqian");
Stu obj2 = (Stu)obj;
System.out.println(obj2.getName());
} catch (InstantiationException e) {
e.printStackTrace();
}
Method mainMethod = three.getMethod("main",String[].class);
Object obj3 = three.getConstructor().newInstance();
Stu obj4 = (Stu)obj3;
mainMethod.invoke(obj4,(Object) new String[]{"a","b","c"});
}
}
|