java反射机制是指在运行状态中,动态获取类的信息(类的属性和方法),以及动态调用对象的方法的功能。
java反射有三个动态性质:
(1)运行时生成对象实例
(2)运行期间调用方法
(3)运行时更改属性
1获取Class对象
(1)调用对象的getClass方法
Class
cla2 = new GirlFirend().getClass();
(2)调用类的class属性
Class
cla1 = GirlFirend
.class;
(3)使用Class类的forName:要使用从根目录开始的地址
Class
cla = Class
.forName("cn.itlaobing.GirlFirend");
2 Class对应的类所包含的构造方法的获取
Constructor constructor1
= cla
.getDeclaredConstructor(Class
[] params
);
Constructor constructor2
= cla
.getConstructor(Class
[] params
);
Constructor
[] constructors1
= cla
.getConstructors();
Constructor
[] constructors2
= cla
.getDeclaredConstructors();
3 通过获取的构造方法创建对象
Class
cla = Date
.class;
Date date
= (Date
) cla
.newInstance();
Constructor c
= date
.getControcture(long.class);
Data d
= (Date
) cla
.newInstance(9999);
4 获取Class对应的类的属性并给它的实例赋值
Field field
= new Class.getField(String name
)
Field field
= new Class.getDeclaredField(String name
)
Field
[] fields
= new Class.getFields()
Field
[] fields
= new Class.getDeclaredFields()
Class
<GirlFirend> girlFirendClass
=GirlFirend
.class;
Constructor constructor
= girlFirendClass
.getDeclaredConstructor();
constructor
.setAccessible(true);
GirlFirend girlFirend
= (GirlFirend
) constructor
.newInstance();
Field field
= girlFirendClass
.getDeclaredField("name");
field
.setAccessible(true);
field
.set(girlFirend
,"long");
System
.out
.println(girlFirend
);
5 获取Class对应的类的方法并让它的实例调用方法
Method method
= class.getMethod(String name
,Class
[] params
)
Method method
= class.getDeclaredMethod(String name
,Class
[] params
)
Method
[] methods
= class.getMethods()
Method
[] methods
= class.getDeclaredMethods()
Class
<GirlFirend> girlFirendClass
= GirlFirend
.class;
Constructor
<GirlFirend> constructor
= girlFirendClass
.getDeclaredConstructor();
if (Modifier
.isPrivate(constructor
.getModifiers())){
constructor
.setAccessible(true);
}
GirlFirend girlFirend
=constructor
.newInstance();
Method method
= girlFirendClass
.getDeclaredMethod("say", String
.class);
method
.invoke(girlFirend
,"zeyu");
6 数组类Array在反射中的使用
Object array
= Array
.newInstance(String
.class,6);
Array
.set("array",5,"aaa");
Array
.set("array",3,"aaa
);
Array、
.get("array",5);
Array、
.get("array",3);
转载请注明原文地址:https://tech.qufami.com/read-17302.html