import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
/**
* <p>Utility class that uses {@code java.lang.reflect} standard library.
* It provides easy access to the standard reflect methods that are
* needed usually when dealing with generic object types.</p>
*/
public class ReflectionUtil {
/**
* When {@code Type} initialized with a value of an object, its fully qualified class name
* will be prefixed with this.
*
* @see {@link ReflectionUtil#getClassName(Type)}
*/
private static final String TYPE_CLASS_NAME_PREFIX = "class ";
private static final String TYPE_INTERFACE_NAME_PREFIX = "interface ";
/*
* Utility class with static access methods, no need for constructor.
*/
private ReflectionUtil() {}
/**
* {@link Type#toString()} value is the fully qualified class name prefixed
* with {@link ReflectionUtil#TYPE_NAME_PREFIX}. This method will substring it, for it to be eligible
* for {@link Class#forName(String)}.
*
* @param type the {@code Type} value whose class name is needed.
* @return {@code String} class name of the invoked {@code type}.
*
* @see {@link ReflectionUtil#getClass()}
*/
public static String getClassName(Type type) {
if (type==null) {
return "";
}
String className = type.toString();
if (className.startsWith(TYPE_CLASS_NAME_PREFIX)) {
className = className.substring(TYPE_CLASS_NAME_PREFIX.length());
} else if (className.startsWith(TYPE_INTERFACE_NAME_PREFIX)) {
className = className.substring(TYPE_INTERFACE_NAME_PREFIX.length());
}
return className;
}
/**
* Returns the {@code Class} object associated with the given {@link Type}
* depending on its fully qualified name.
*
* @param type the {@code Type} whose {@code Class} is needed.
* @return the {@code Class} object for the class with the specified name.
*
* @throws ClassNotFoundException if the class cannot be located.
*
* @see {@link ReflectionUtil#getClassName(Type)}
*/
public static Class<?> getClass(Type type)
throws ClassNotFoundException {
String className = getClassName(type);
if (className==null || className.isEmpty()) {
return null;
}
return Class.forName(className);
}
/**
* Creates a new instance of the class represented by this {@code Type} object.
*
* @param type the {@code Type} object whose its representing {@code Class} object
* will be instantiated.
* @return a newly allocated instance of the class represented by
* the invoked {@code Type} object.
*
* @throws ClassNotFoundException if the class represented by this {@code Type} object
* cannot be located.
* @throws InstantiationException if this {@code Type} represents an abstract class,
* an interface, an array class, a primitive type, or void;
* or if the class has no nullary constructor;
* or if the instantiation fails for some other reason.
* @throws IllegalAccessException if the class or its nullary constructor is not accessible.
*
* @see {@link Class#newInstance()}
*/
public static Object newInstance(Type type)
throws ClassNotFoundException, InstantiationException, IllegalAccessException {
Class<?> clazz = getClass(type);
if (clazz==null) {
return null;
}
return clazz.newInstance();
}
/**
* Returns an array of {@code Type} objects representing the actual type
* arguments to this object.
* If the returned value is null, then this object represents a non-parameterized
* object.
*
* @param object the {@code object} whose type arguments are needed.
* @return an array of {@code Type} objects representing the actual type
* arguments to this object.
*
* @see {@link Class#getGenericSuperclass()}
* @see {@link ParameterizedType#getActualTypeArguments()}
*/
public static Type[] getParameterizedTypes(Object object) {
Type superclassType = object.getClass().getGenericSuperclass();
if (!ParameterizedType.class.isAssignableFrom(superclassType.getClass())) {
return null;
}
return ((ParameterizedType)superclassType).getActualTypeArguments();
}
/**
* Checks whether a {@code Constructor} object with no parameter types is specified
* by the invoked {@code Class} object or not.
*
* @param clazz the {@code Class} object whose constructors are checked.
* @return {@code true} if a {@code Constructor} object with no parameter types is specified.
* @throws SecurityException If a security manager, <i>s</i> is present and any of the
* following conditions is met:
* <ul>
* <li> invocation of
* {@link SecurityManager#checkMemberAccess
* s.checkMemberAccess(this, Member.PUBLIC)} denies
* access to the constructor
*
* <li> the caller's class loader is not the same as or an
* ancestor of the class loader for the current class and
* invocation of {@link SecurityManager#checkPackageAccess
* s.checkPackageAccess()} denies access to the package
* of this class
* </ul>
*
* @see {@link Class#getConstructor(Class...)}
*/
public static boolean hasDefaultConstructor(Class<?> clazz) throws SecurityException {
Class<?>[] empty = {};
try {
clazz.getConstructor(empty);
} catch (NoSuchMethodException e) {
return false;
}
return true;
}
/**
* Returns a {@code Class} object that identifies the
* declared class for the field represented by the given {@code String name} parameter inside
* the invoked {@code Class<?> clazz} parameter.
*
* @param clazz the {@code Class} object whose declared fields to be
* checked for a certain field.
* @param name the field name as {@code String} to be
* compared with {@link Field#getName()}
* @return the {@code Class} object representing the type of given field name.
*
* @see {@link Class#getDeclaredFields()}
* @see {@link Field#getType()}
*/
public static Class<?> getFieldClass(Class<?> clazz, String name) {
if (clazz==null || name==null || name.isEmpty()) {
return null;
}
Class<?> propertyClass = null;
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
if (field.getName().equalsIgnoreCase(name)) {
propertyClass = field.getType();
break;
}
}
return propertyClass;
}
/**
* Returns a {@code Class} object that identifies the
* declared class as a return type for the method represented by the given
* {@code String name} parameter inside the invoked {@code Class<?> clazz} parameter.
*
* @param clazz the {@code Class} object whose declared methods to be
* checked for the wanted method name.
* @param name the method name as {@code String} to be
* compared with {@link Method#getName()}
* @return the {@code Class} object representing the return type of the given method name.
*
* @see {@link Class#getDeclaredMethods()}
* @see {@link Method#getReturnType()}
*/
public static Class<?> getMethodReturnType(Class<?> clazz, String name) {
if (clazz==null || name==null || name.isEmpty()) {
return null;
}
name = name.toLowerCase();
Class<?> returnType = null;
for (Method method : clazz.getDeclaredMethods()) {
if (method.getName().equals(name)) {
returnType = method.getReturnType();
break;
}
}
return returnType;
}
/**
* Extracts the enum constant of the specified enum class with the
* specified name. The name must match exactly an identifier used
* to declare an enum constant in the given class.
*
* @param clazz the {@code Class} object of the enum type from which
* to return a constant.
* @param name the name of the constant to return.
* @return the enum constant of the specified enum type with the
* specified name.
*
* @throws IllegalArgumentException if the specified enum type has
* no constant with the specified name, or the specified
* class object does not represent an enum type.
*
* @see {@link Enum#valueOf(Class, String)}
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Object getEnumConstant(Class<?> clazz, String name) {
if (clazz==null || name==null || name.isEmpty()) {
return null;
}
return Enum.valueOf((Class<Enum>)clazz, name);
}
}
- 浏览: 347349 次
- 性别:
- 来自: 沈阳
文章分类
最新评论
-
haiw:
谢谢分享
Oracle 的递归查询(树型查询) -
nomandia:
除非是通过open打开的窗口,否则没法close的
JS 关闭当前页面 -
c30989239:
注意 SimpleDateFormat 是非线程安全的
Java 获取网络时间并在jsp中显示 -
归来朝歌:
不错,以后可能用得上
Java 操作Excel -
luhantu:
不错!学习了
Java 操作Excel
发表评论
-
springmvc整合cxf webservice
2016-03-15 16:54 1323springmvc中整合cxf webservice。 ... -
JSTL fn函数中字符串拼接
2015-11-30 11:35 5263关于JSTL的标签,在网上查了很久,都是介绍fn ... -
Java 获取网络时间并在jsp中显示
2015-09-07 14:15 1894开发中经常会遇到需要将服务器时间或者网络时间显示在 ... -
JSTL foreach及if when标签使用
2015-07-22 08:48 2091需要在jsp中加入以下标签库和函数库 <%@ ta ... -
Java 获取服务器IP和本地Ip
2015-07-21 21:39 8731在项目中经常会遇到需要获取服务器的IP和本地IP, ... -
Mybatis 模糊查询
2015-06-11 18:42 657参数中直接加入%% param.setUsernam ... -
MyBatis之增加删除修改
2015-06-11 16:32 1697insert、update、delete这三个元素分别用于执行 ... -
MyBatis 传入参数parameterType详解
2015-06-11 16:29 18795在MyBatis的select、insert、update ... -
Java 操作Excel
2015-06-10 20:54 2318前不久做过Excel的导入导出功能,其主要的难点是java如何 ... -
SpringMVC+mybatis 实现easyui中tree
2015-06-08 22:08 5329最近做项目用到了前端框架easyUI,以下是easyUI ... -
MD5加密工具类
2015-06-03 18:47 1348package base; /** * MD5加密算法 * ... -
spring+mybatis配置
2015-02-08 17:04 8831.用spring配置mybatis <?xml ver ... -
JAVA 处理JSON工具类
2014-12-31 13:49 1603以下代码为Java处理json数据的工具类,以备后用 pac ... -
Java解析及读取Json数据
2014-12-31 13:46 18701.JSON介绍 JSON比XML简单,主要体现在传输相 ... -
新版SSH整合(备用)
2014-09-01 19:40 1656在网上找的S4S2H4架构实现,现记录一下,以备后用。 附件中 ... -
jsp静态化和伪静态化
2014-06-12 16:21 833首先说说为什么要静态化。 对于现在的Web Applicat ... -
Struts2实现Excel导入
2014-05-28 17:15 2613除Struts2必须的jar包外,还需要jar包:poi ... -
JSP自定义标签的创建和使用
2014-04-18 10:45 1266摘自http://jzinfo.iteye.com/blog/ ... -
ssh项目中strust2从2.0.11升级到2.3.15.1详细步骤
2014-03-28 15:33 2240将ssh项目中strust2从2.0.11升级到2.3.15. ... -
MyEclipse下创建的项目 导入eclipse(转载)
2014-03-19 17:15 814FROM:http://www.cnblogs.com/zho ...
相关推荐
ReflectionUtil 反射工具包,利用反射的API直接生成Java字节码,提高执行效率。 ###普通方法调用 所有的命令最终生成到Invoker对象的invoke方法中 public Object invoke(Object[] args); 具体使用如下: ...
Java开发中中经常使用的Java工具类分享,工作中用得上,直接拿来使用,不用重复造轮子。
----------Database-------------- ...(ReflectionUtil.cs) 注册表操作辅助类(RegistryHelper.cs) 用于验证码图片识别的类(UnCodebase.cs) 将原始字串转换为unicode,格式为\u.\u.( UnicodeHelper.cs)
----------Database-------------- ...(ReflectionUtil.cs) 13. 注册表操作辅助类(RegistryHelper.cs) 14. 用于验证码图片识别的类(UnCodebase.cs) 15. 将原始字串转换为unicode,格式为\u.\u.( UnicodeHelper.cs)
----------Database-------------- ...(ReflectionUtil.cs) 13.注册表操作辅助类(RegistryHelper.cs) 14.用于验证码图片识别的类(UnCodebase.cs) 15.将原始字串转换为unicode,格式为\u.\u.( UnicodeHelper.cs)
Reflection-util:Java反射实用程序请参阅。编辑您的构建文件您可以从获得Reflection-util库。 在gradle构建文件中,编写dependencies { implementation 'org.plumelib:reflection-util:1.0.3'}其他构建系统为 。
最后,xwork-2.2.1的源代码还包含了大量的实用工具类,如反射工具类ReflectionUtil、类型判断工具ClassUtils等,这些都是日常开发中不可或缺的部分。通过研究这些工具类,开发者可以学习到更多关于Java反射、泛型等...
记录仪记录更多详细的类,方法和行号键盘实用程序显示/隐藏键盘ReflectionUtil 通过反射获得/吸收ToastUtil 显示吐司的捷径AddOnScrollListenerUtil 未set但add AbsListView.OnScrollListener MainThreadCallback ...
7. **反射和类型转换**:ReflectionUtil可能用于动态获取类信息、创建对象、调用私有方法等。 8. **枚举操作**:EnumUtil可能包含处理枚举类型的工具方法,如获取枚举值、枚举转换等。 9. **验证和校验**:Validator...
public class ReflectionUtil { public static void invokeMethodByProperty(Properties props, Object targetObject) { for (String key : props.stringPropertyNames()) { String methodName = "set" + key....
这是本文将要介绍的ReflectionUtil是为了解决这类问题的辅助工具类,为java.lang.reflect标准库的工具类。它提供了便捷的访问泛型对象类型(java.reflect.Type)的反射方法。 本文假设你已经了解java反射知识,并能...
public class ReflectionUtil { private static class ReflectCache { private static final Map, Class<?>> CLASS_CACHE = new ConcurrentHashMap(); // ...其他反射对象的缓存 } public static Class<?> ...
JsonResult、PageBean、exception、excel、FtpHelper、HttpHelper、AESHelper、DESHelper、RSAHelper、ChineseUtil、ClassUtil、...PropertiesLoader、ReflectionUtil、StringUtil、ValidatorUtil、ZipUtil
9. **ReflectionUtil.cs**: 反射是.NET Framework的一个强大特性,ReflectionUtil可能是对反射的封装,提供了一些方便的方法来动态创建对象、获取成员信息、调用方法等。 10. **GZipUtil.cs**: 最后,GZipUtil可能...
`ReflectionUtil`是一个工具类,它扩展了Java标准库中的`java.lang.reflect`,提供了一些便捷的方法来处理泛型。这个类主要包含了以下几个功能: 1. **通过Type获取对象Class**: `getClassName(Type type)`方法...
最后,`util`文件名可能包含了一个名为`ReflectionUtil`或`AjaxJsonUtil`的工具类,该类封装了上述的反射赋值和JSON转换逻辑,提供了一种简洁的方式来处理这些常见的任务。这样的工具类提高了代码的复用性,降低了...