百度了下为啥要使用反射,也没有看出个所以然来。
这里根据最近做的一个功能(使用了注解开发)讲下自己对反射的理解。
javaCode:
public static BeanLuceneExtend objToLuceneExtend(Object obj)
{
try
{
if(obj == null)
{
return null;
}
// 得到类的抽象数据类型
Class clazz = obj.getClass();
if(clazz.isAnnotationPresent(VoToLuceneAnnotation.class))
{
StringBuilder content = new StringBuilder();
String id= null;
String title = null;
String type = null;
VoToLuceneAnnotation vo = (VoToLuceneAnnotation) clazz.getAnnotation(VoToLuceneAnnotation.class);
// 获取类上注解的值
type = vo.type();
LOG.info(String.format("****start to make id,and type is %s****", type));
Field[] fields = clazz.getDeclaredFields();
for(Field f : fields)
{
if(f.isAnnotationPresent(VoFieldToLuceneAnnotation.class))
{
VoFieldToLuceneAnnotation voF = f.getAnnotation(VoFieldToLuceneAnnotation.class);
if(voF.name().equalsIgnoreCase(LuceneExtendFieldEnum.ID.toString()))
{
LOG.info("****start to make id****");
if(!f.isAccessible())
{
f.setAccessible(true);
id = (String) f.get(obj);
}
}else if (voF.name().equalsIgnoreCase(LuceneExtendFieldEnum.TITLE.toString()))
{
LOG.info("****start to make title****");
if(!f.isAccessible())
{
f.setAccessible(true);
title = (String) f.get(obj);
content.append((String) f.get(obj)).append(" ");
}
}else if(voF.name().equalsIgnoreCase(LuceneExtendFieldEnum.CONTENT.toString()))
{
LOG.info("****start to make content****");
if(!f.isAccessible())
{
f.setAccessible(true);
content.append(f.get(obj)).append(" ");
}
}
}
}
return makeParam(id, type, title, content);
}
}catch(Exception e)
{
LOG.error("构造BeanLunceneExtend对象失败 " + e.toString());
}
return null;
}
以上代码是将普通对象转成BeanLuceneExtend对象(请忽略),注意看入参,由于这个是公共的方法,没有具体的入参VO类型,所以使用了顶级父类Object。
接下来我需要使用到每个VO中成员变量的值,因为入参类型是Object,所以无法向下转型为具体的类,也就无法使用get()方法获取。这时反射就起了巨大作用,不用知道具体的VO是什么,如果有成员变量就能知道这个成员变量的值。
以上就是我对反射的一点理解。