记录下JAVA反射用法,应用场景就不提了,这里只提用法
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException, NoSuchFieldException {
Class<?> reflectionClass = Reflection.class;
Constructor c = reflectionClass.getConstructor(null);
Object r= c.newInstance();//构造器实例
Constructor c2 = reflectionClass.getConstructor(String.class);
c2.newInstance("hello");
Constructor c3 = reflectionClass.getConstructor(String.class,int.class);
c3.newInstance("小明",13);
System.out.println();
//通过反射获取实例的方法
Method method1=reflectionClass.getMethod("getName"); //获取共有getName方法
Method method2=reflectionClass.getMethod("getAge"); //获取共有getAge方法
Method method3=reflectionClass.getDeclaredMethod("setName",String.class); //获取私有setName方法 参数String
Method method4=reflectionClass.getDeclaredMethod("setAge",int.class); //获取私有setAge方法 参数String
method3.setAccessible(true); //设置操作权限
method4.setAccessible(true); //设置操作权限
method3.invoke(r,"小明"); //调用setName()
method4.invoke(r,14); //调用setAge()
System.out.println(method1.invoke(r)); //调用getName()
System.out.println(method2.invoke(r)); //调用getAge()
Field field =reflectionClass.getField("name"); //获取共有字段name
Field field2=reflectionClass.getDeclaredField("age");//获取私有字段age
field2.setAccessible(true); //设置私有字段可访问
System.out.println("\n============================修改前Feild的值=================================");
System.out.println(field.getName()+":"+field.get(r)+"\t访问权限:"+field.getModifiers()+"\t"+field.getType());
System.out.println(field2.getName()+":"+field2.get(r)+"\t访问权限:"+field2.getModifiers()+"\t"+field2.getType());
field.set(r,"小米"); //修改name字段的值
field2.set(r,15); //修改age字段的值
System.out.println("\n============================修改后Feild的值=================================");
System.out.println(field.getName()+":"+field.get(r)+"\t访问权限:"+field.getModifiers()+"\t"+field.getType());
System.out.println(field2.getName()+":"+field2.get(r)+"\t访问权限:"+field2.getModifiers()+"\t"+field2.getType());
}
Reflection.java
public class Reflection {
public String name;
private int age;
public Reflection() {
System.out.println("无参构造器");
}
public Reflection(String a) {
System.out.println("有参构造器:" + a);
}
public Reflection(String name, int age) {
System.out.println("多参构造器:" + name + "\t" + age);
}
private void setName(String name) {
this.name = name;
}
private void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
运行结果: