反射 —— 超级全面
实体类
class ReflectExample
{
public String str;
private int id;
public ReflectExample()
{
System.out.println("public无参构造函数");
}
public ReflectExample(int id)
{
this.id =id;
System.out.println("public 有参构造函数 id");
System.out.println("元素id属性值"+this.id);
}
private ReflectExample(int id,String str)
{
this.id =id;
this.str =str;
System.out.println("private 参构造函数 id str ");
System.out.println("元素str的值"+this.str+"元素的id值"+this.id);
}
public void show1()
{
System.out.println("public 无参函数 ");
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void show(String str , int a)
{
System.out.println("public 有参函数String + int");
}
public void show(int b)
{
System.out.println("public 有参函数int");
System.out.println("显示函数 "+b);
}
private void show2()
{
System.out.println("显示参数 "+id);
System.out.println("private 无参函数 ");
}
}
测试类 包含所有的公有私有有参无参的构造函数 函数 还有 私有公有的成员变量
package test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
public class Demo6 {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
//三种不同的获取class对象的方式
Class class1 = Class.forName("test.ReflectExample");// 最推荐 类名要是全名
Class class2 = new ReflectExample().getClass();// 需要创建实体类
Class class3 = ReflectExample.class; //必须对该类可见
ReflectExample reflectExample1 = (ReflectExample) class1.newInstance();//使用无参构造函数创建对象
System.out.println(reflectExample1);
//使用有参构造函数创建对象
Constructor constructor1 = class2.getDeclaredConstructor(int.class);
ReflectExample reflectExample2 = (ReflectExample) constructor1.newInstance(2);
System.out.println(reflectExample2);
Constructor constructor2 = class2.getDeclaredConstructor(int.class ,String.class);
constructor2.setAccessible(true);
ReflectExample reflectExample3 = (ReflectExample) constructor2.newInstance(2,"yuniko");
System.out.println(reflectExample3);
//获取字段
Field field = class1.getField("str");
field.set(reflectExample1, "留下");
Field field1 = class1.getDeclaredField("id");
field1.setAccessible(true);
field1.set(reflectExample1, 2);
System.out.println("设置后的值str "+reflectExample1.getStr()+"id "+reflectExample1.getId());
//获取私有公有的方法
Method method1 = class1.getDeclaredMethod("show",int.class);
// 如果底层方法是静态的,那么可以忽略指定的 obj 参数。该参数可以为 null。
//
//如果底层方法所需的形参数为 0,则所提供的 args 数组长度可以为 0 或 null。
method1.invoke(reflectExample1, 1);
method1.invoke(reflectExample1, 1);
Method method2 = class1.getDeclaredMethod("show2", null);
method2.setAccessible(true);
method2.invoke(reflectExample1, null);
method2.invoke(reflectExample1, null);
}
}