个人理解JAVA反射

百度了下为啥要使用反射,也没有看出个所以然来。

这里根据最近做的一个功能(使用了注解开发)讲下自己对反射的理解。

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是什么,如果有成员变量就能知道这个成员变量的值。

以上就是我对反射的一点理解。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值