package com.sshex.demo.utils;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* Created by Administrator on 2015/12/4.
*/
public class ReflectionUtils {
private static Logger logger = LoggerFactory.getLogger(ReflectionUtils.class);
/**
* 调用Getter方法.
*/
public static Object invokeGetterMethod(Object obj, String propertyName) {
String getterMethodName = "get" + StringUtils.capitalize(propertyName);
return invokeMethod(obj, getterMethodName, new Class[] {}, new Object[] {});
}
/**
* 调用Setter方法.使用value的Class来查找Setter方法.
*/
public static void invokeSetterMethod(Object obj, String propertyName, Object value) {
invokeSetterMethod(obj, propertyName, value, null);
}
/**
* 调用Setter方法.
*
* @param propertyType 用于查找Setter方法,为空时使用value的Class替代.
*/
public static void invokeSetterMethod(Object obj, String propertyName, Object value, Class<?> propertyType) {
Class<?> type = propertyType != null ? propertyType : value.getClass();
String setterMethodName = "set" + StringUtils.capitalize(propertyName);
invokeMethod(obj, setterMethodName, new Class[] { type }, new Object[] { value });
}
/**
* 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数.
*/
public static Object getFieldValue(final Object obj, final String fieldName) {
Field field = getAccessibleField(obj, fieldName);
if (field == null) {
throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
}
Object result = null;
try {
result = field.get(obj);
} catch (IllegalAccessException e) {
logger.error("不可能抛出的异常{}", e.getMessage());
}
return result;
}
/**
* 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
*/
public static void setFieldValue(final Object obj, final String fieldName, final Object value) {
Field field = getAccessibleField(obj, fieldName);
if (field == null) {
throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
}
try {
field.set(obj, value);
} catch (IllegalAccessException e) {
logger.error("不可能抛出的异常:{}", e.getMessage());
}
}
/**
* 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问.
*
* 如向上转型到Object仍无法找到, 返回null.
*/
public static Field getAccessibleField(final Object obj, final String fieldName) {
Assert.notNull(obj, "object不能为空");
Assert.hasText(fieldName, "fieldName");
for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
try {
Field field = superClass.getDeclaredField(fieldName);
field.setAccessible(true);
return field;
} catch (NoSuchFieldException e) {//NOSONAR
// Field不在当前类定义,继续向上转型
}
}
return null;
}
/**
* 直接调用对象方法, 无视private/protected修饰符.
* 用于一次性调用的情况.
*/
public static Object invokeMethod(final Object obj, final String methodName, final Class<?>[] parameterTypes,
final Object[] args) {
Method method = getAccessibleMethod(obj, methodName, parameterTypes);
if (method == null) {
throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]");
}
try {
return method.invoke(obj, args);
} catch (Exception e) {
throw convertReflectionExceptionToUnchecked(e);
}
}
/**
* 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问.
* 如向上转型到Object仍无法找到, 返回null.
*
* 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
*/
public static Method getAccessibleMethod(final Object obj, final String methodName,
final Class<?>... parameterTypes) {
Assert.notNull(obj, "object不能为空");
for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
try {
Method method = superClass.getDeclaredMethod(methodName, parameterTypes);
method.setAccessible(true);
return method;
} catch (NoSuchMethodException e) {//NOSONAR
// Method不在当前类定义,继续向上转型
}
}
return null;
}
/**
* 通过反射, 获得Class定义中声明的父类的泛型参数的类型.
* 如无法找到, 返回Object.class.
* eg.
* public UserDao extends HibernateDao<User>
*
* @param clazz The class to introspect
* @return the first generic declaration, or Object.class if cannot be determined
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> Class<T> getSuperClassGenricType(final Class clazz) {
return getSuperClassGenricType(clazz, 0);
}
/**
* 通过反射, 获得Class定义中声明的父类的泛型参数的类型.
* 如无法找到, 返回Object.class.
*
* 如public UserDao extends HibernateDao<User,Long>
*
* @param clazz clazz The class to introspect
* @param index the Index of the generic ddeclaration,start from 0.
* @return the index generic declaration, or Object.class if cannot be determined
*/
@SuppressWarnings("rawtypes")
public static Class getSuperClassGenricType(final Class clazz, final int index) {
Type genType = clazz.getGenericSuperclass();
if (!(genType instanceof ParameterizedType)) {
logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
return Object.class;
}
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
+ params.length);
return Object.class;
}
if (!(params[index] instanceof Class)) {
logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
return Object.class;
}
return (Class) params[index];
}
/**
* 将反射时的checked exception转换为unchecked exception.
*/
public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) {
if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException
|| e instanceof NoSuchMethodException) {
return new IllegalArgumentException("Reflection Exception.", e);
} else if (e instanceof InvocationTargetException) {
return new RuntimeException("Reflection Exception.", ((InvocationTargetException) e).getTargetEx
没有合适的资源?快使用搜索试试~ 我知道了~
SpringMVC-MongoDB的Restful Demo工程
共99个文件
xml:53个
class:17个
java:17个
4星 · 超过85%的资源 需积分: 9 37 下载量 20 浏览量
2015-12-07
14:26:21
上传
评论
收藏 38KB 7Z 举报
温馨提示
1、利用SpringMVC+Spring+MongoDb搭建的Rest api工程 2、利用localhost:8080/demo/user/register可以测试(会在本地MongoDB中形成user数据) 3、利用maven进行管理 4、IDE:IDEA
资源推荐
资源详情
资源评论
收起资源包目录
demo.7z (99个子文件)
demo
.gitignore 100B
pom.xml 8KB
target
maven-status
maven-compiler-plugin
compile
default-compile
createdFiles.lst 635B
inputFiles.lst 1KB
generated-sources
annotations
classes
config.properties 526B
spring-hibernate.xml 4KB
log4j.properties 531B
mongodb.properties 33B
springmvc.xml 3KB
com
zdaq
edu
utils
dao
impl
model
controller
aop
Entity
service
impl
sshex
demo
utils
HttpClient.class 7KB
ReflectionUtils.class 7KB
JSONObjectWarp.class 894B
dao
BaseExDao.class 3KB
IBaseDao.class 454B
IBaseExDao.class 962B
Page.class 1KB
impl
UserDaoImpl.class 533B
BaseDao.class 2KB
SuperBaseDao.class 1KB
controller
UserController.class 2KB
aop
InterceptorFilter.class 1KB
service
UserService.class 362B
impl
BaseServiceImpl.class 544B
UserServiceImpl.class 1000B
entity
User.class 1KB
spring-mvc.xml 2KB
spring.xml 739B
spring-mongodb.xml 2KB
tomcat
conf
tomcat-users.xml 1KB
web.xml 50KB
work
localEngine
localhost
eduserver
org
apache
jsp
WEB_002dINF
pages
index_jsp.java 2KB
index_jsp.class 4KB
demo
webapps
logs
demo.iml 4KB
src
main
resources
config.properties 526B
spring-hibernate.xml 4KB
log4j.properties 531B
mongodb.properties 33B
spring-mvc.xml 2KB
spring.xml 739B
spring-mongodb.xml 2KB
java
com
sshex
demo
utils
JSONObjectWarp.java 615B
HttpClient.java 6KB
ReflectionUtils.java 8KB
dao
BaseExDao.java 1KB
IBaseDao.java 252B
impl
UserDaoImpl.java 357B
Page.java 833B
BaseDao.java 701B
SuperBaseDao.java 762B
IBaseExDao.java 963B
controller
UserController.java 916B
aop
InterceptorFilter.java 591B
service
UserService.java 323B
impl
BaseServiceImpl.java 250B
UserServiceImpl.java 644B
entity
User.java 777B
webapp
WEB-INF
web.xml 2KB
log4j.xml 2KB
pages
index.jsp 200B
.idea
uiDesigner.xml 9KB
libraries
Maven__javax_servlet_jsp_jsp_api_2_2_1_b03.xml 552B
Maven__commons_fileupload_commons_fileupload_1_2_2.xml 605B
Maven__org_springframework_spring_jdbc_3_2_0_RELEASE.xml 616B
Maven__org_hamcrest_hamcrest_core_1_3.xml 532B
Maven__org_springframework_data_spring_data_mongodb_1_3_0_RELEASE.xml 692B
Maven__javax_servlet_jstl_1_2.xml 473B
Maven__commons_logging_commons_logging_1_1_1.xml 572B
Maven__org_springframework_spring_aop_3_2_0_RELEASE.xml 609B
Maven__org_springframework_spring_orm_3_2_0_RELEASE.xml 609B
Maven__commons_dbcp_commons_dbcp_1_4.xml 525B
Maven__org_springframework_spring_beans_3_2_0_RELEASE.xml 623B
Maven__org_mongodb_mongo_java_driver_2_11_1.xml 577B
Maven__org_springframework_spring_expression_3_2_0_RELEASE.xml 658B
Maven__org_springframework_spring_test_3_2_0_RELEASE.xml 616B
Maven__org_springframework_spring_web_3_2_0_RELEASE.xml 609B
Maven__org_springframework_spring_webmvc_3_2_0_RELEASE.xml 630B
Maven__org_slf4j_jcl_over_slf4j_1_7_1.xml 541B
Maven__commons_pool_commons_pool_1_5_4.xml 539B
Maven__org_springframework_spring_tx_3_1_4_RELEASE.xml 602B
Maven__org_springframework_spring_context_3_2_0_RELEASE.xml 637B
Maven__org_aspectj_aspectjweaver_1_7_1.xml 542B
Maven__org_springframework_data_spring_data_commons_1_6_0_RELEASE.xml 692B
Maven__log4j_log4j_1_2_17.xml 469B
Maven__org_codehaus_jackson_jackson_mapper_asl_1_9_11.xml 620B
Maven__org_codehaus_jackson_jackson_core_asl_1_9_11.xml 606B
Maven__org_springframework_spring_core_3_2_0_RELEASE.xml 616B
Maven__com_alibaba_fastjson_1_1_26.xml 514B
Maven__junit_junit_4_11.xml 455B
Maven__aopalliance_aopalliance_1_0.xml 514B
Maven__javax_servlet_servlet_api_3_0_alpha_1.xml 578B
Maven__org_slf4j_slf4j_api_1_7_1.xml 506B
workspace.xml 71KB
encodings.xml 273B
vcs.xml 183B
misc.xml 1KB
modules.xml 248B
.name 4B
copyright
profiles_settings.xml 76B
compiler.xml 2KB
共 99 条
- 1
资源评论
- daniel_dx2016-01-27还算可以吧...简单的demo, 需要的都有了.
WW.SS
- 粉丝: 1
- 资源: 4
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功