反射:java反射就是在运行时动态获取类的各个组成部分的信息,包括属性、方法、构造方法、注解、接口、父类等。
这里以ReflectClass类为例,以下是一个放射类的操作实例:
package util;
import model.MethodInfo;
import model.Test;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* 注:ReflectClass reflectClass = new ReflectClass();
reflectClass.initClass("model.App");
reflectClass.initConstructor();
reflectClass.initObject();
reflectClass.getAnnotationInfos();
*/
public class ReflectClass {
/**
* 即将要被反射的Class对象
*/
private Class<?> mClazz;
/**
* 被放射对象的实例
*/
private Object mObj;
/**
* 构造函数对象
*/
private Constructor<?> constructor;
public ReflectClass(){}
/**
* 初始化反射类的Class对象,并实例化
* @param className
*/
public void initClass(String className) throws Exception {
mClazz = Class.forName(className);
}
/**
* 获取构造函数对象
* @param paramTypes
* @throws Exception
*/
public void initConstructor(Class<?>... paramTypes) throws Exception {
constructor = mClazz.getConstructor(paramTypes);
}
public void initObject(String... param) throws Exception {
mObj = constructor.newInstance(param);
}
public Object invoke(String methodName,Object... args) throws Exception {
Method method = mClazz.getDeclaredMethod(methodName);
return method.invoke(mObj,args);
}
/**
* 为属性设置值
* @param name
* @param grade
* @throws Exception
*/
public void setField(String name,int grade) throws Exception {
Field field = mClazz.getDeclaredField("mGrade");
field.setAccessible(true);
field.set(mObj,grade);
}
/**
* 获取父类
*/
public void getSuperClass(){
Class<?> superClass = mClazz.getSuperclass();
while(superClass !=null){
System.out.println(superClass.getName());
superClass = superClass.getSuperclass();
}
}
/**
* 获取接口
*/
public void showInterface(){
Class<?>[] interfaces = mClazz.getInterfaces();
for(Class<?> i : interfaces){
System.out.println(i.getName());
}
}
public void getAnnotationInfos() throws Exception {
Method method = mClazz.getMethod("getAppName");
Annotation[] annotations = method.getAnnotations();
for(Annotation annotation : annotations){
if(method.isAnnotationPresent(MethodInfo.class)){
MethodInfo methodInfo = (MethodInfo) annotation;
System.out.println(methodInfo.author());
System.out.println(methodInfo.date());
System.out.println(methodInfo.version());
}
}
}
public void showFields(){
Field[] fields = mClazz.getFields();
//获取当前类以及父类的所有公有属性
for(Field f : fields){
System.out.println(f.getName());
}
}
public void setFieldFromAnnotation()throws Exception{
//获取私有的属性(包括private、protected),只能获取当前类
Field field = mClazz.getSuperclass().getDeclaredField("mName");
field.setAccessible(true);
Test test = field.getAnnotation(Test.class);
// Object obj = mClazz.getSuperclass().getConstructor().newInstance();
field.set(mObj,test.name());
}
}