您的位置:首页 > 编程语言 > Java开发

java反射

2016-05-20 00:00 507 查看
摘要: java反射的简单应用

目前是jdk1.8,主要结合此进行;
#1. 获取字段

MonthTask monthTask = monthTaskrep.getOne(mainTaskId + 0L);
Class<? extends MonthTask> mclass = monthTask.getClass();
Field field= mclass.getDeclaredField(name);
Object val=field.get(monthTask);

根据实例获取class,然后用class的到field,然后通过field来获取结果,常用Field.get(Class的instance),当然还有其他获取值得方法,如Field.getString(instance),Field.getInteger(instance);

#2. 调用方法

Method method =mclass.getDeclaredMethod("getTal" + i + "goal") ;//1
Object o= method.invoke(monthTask);//2


1.从class中获取方法对象,mclass.getDeclaredMethod(String methodName,Class<?>... parameterTypes),第二个位置为参数列表;
貌似jdk1.8不支持直接获取private类型的field,然后只能用method去取了;在获取set方法时,结果没写参数列表,所以的到的方法时null;:joy:

2.method.invoke(instance,Object... args);第二位置为该方法参数实例,如
method.invoke(instance,1,"圣斗士",5L);

#3. 构造实例

Class<? extends MonthTask> mclass = monthTask.getClass();
MonthTask monthTask=  mclass.newInstance();

这个monthTask需要你去赋值;即通过获取各种set方法去赋值;各种javaBean都是通过这种方式构造的;
当然MonthTask类必须符合javaBean的标准;
ORM的映射也是通过反射实现的,

#4. 获取元数据(注解)

<A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass){

}
Entity entity= mclass.getDeclaredAnnotation(Entity.class);


获取了一个在mclass类上的Entity注解entity的实例,然后通过该entity和mclass在一起将其转化成具体的数据库的table;具体代码缺;

#5. 获取实现的接口

Class<?> classz=new ArrayList<String>().getClass();
classz=ArrayList.class;
Class<?> [] interfaces= classz.getInterfaces()();
for(Class<?>  interface:interfaces){
System.out.println(interface.getName());
}


输出会包含 java.lang.List; 因为ArrayList实现了List接口;
可以通过继承的接口来判断该类有什么方法;或者对其进行针对性的操作;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  reflect 反射