反射方面的知识记录

原创
2014/03/26 17:17
阅读数 232

Class<?> clazz = entity.getClass();
String className = nameHandler.getTableName(clazz.getSimpleName());


// 获取属性信息
BeanInfo beanInfo = getSelfBeanInfo(clazz);
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor pd : pds)
{
Object value = getReadMethodValue(pd.getReadMethod(), entity);
if (value == null)
{
continue;
}
String columnName = getColumnName(pd.getName());
}


private static Object getReadMethodValue(Method readMethod, Object entity)
{
if (readMethod == null)
{
return null;
}
try
{
if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers()))
{
readMethod.setAccessible(true);
}
return readMethod.invoke(entity);
}
catch (Exception e)
{
LOG.error("获取属性值失败", e);
e.printStackTrace();
}
return null;
}




----------------------------------------------------------------------------------------

package com.yuma.lh.utils;



import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 类辅助
 */
public class ClassUtils
{


/** 日志对象 */
private static final Logger LOG = LoggerFactory.getLogger(ClassUtils.class);


/**
* Map keyed by class containing CachedIntrospectionResults. Needs to be a
* WeakHashMap with WeakReferences as values to allow for proper garbage
* collection in case of multiple class loaders.
*/
private static final Map<Class, BeanInfo> classCache = Collections.synchronizedMap(new WeakHashMap<Class, BeanInfo>());


/**
* 获取类本身的BeanInfo,不包含父类属性

* @param clazz
* @return
*/
public static BeanInfo getSelfBeanInfo(Class<?> clazz)
{
BeanInfo beanInfo = null;
try
{
if (classCache.get(clazz) == null)
{
beanInfo = Introspector.getBeanInfo(clazz, clazz.getSuperclass());
classCache.put(clazz, beanInfo);
// Immediately remove class from Introspector cache, to allow  for proper
// garbage collection on class loader shutdown - we cache it  here anyway,
// in a GC-friendly manner. In contrast to  CachedIntrospectionResults,
// Introspector does not use WeakReferences as values of its WeakHashMap!
Class classToFlush = clazz;
do
{
Introspector.flushFromCaches(classToFlush);
classToFlush = classToFlush.getSuperclass();
} while (classToFlush != null);
}
else
{
beanInfo = classCache.get(clazz);
}
}
catch (IntrospectionException e)
{
LOG.error("获取BeanInfo失败", e);
e.printStackTrace();
}
return beanInfo;
}


/**
* 初始化实例

* @param clazz
* @return
*/
public static Object newInstance(Class<?> clazz)
{
try
{
return clazz.newInstance();
}
catch (Exception e)
{
LOG.error("根据class创建实例失败", e);
e.printStackTrace();
}
return null;
}
}
展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
7 收藏
0
分享
返回顶部
顶部