您的位置:首页 > 编程语言 > Java开发

java反射最常用的几个方法

2018-04-06 13:05 393 查看
1.获取javaBean的属性

Student s = new Student();
Class<? extends Student> class1 = s.getClass();
//获取public的属性
Field[] fields = class1.getFields();
//获取所有的属性
Field[] declaredFields = class1.getDeclaredFields();
for(Field f:fields) {
System.out.println("***执行getFields()方法***");
System.out.println(f);
}
for(Field f:declaredFields) {
System.out.println("***执行getDeclaredFields()方法***");
System.out.println(f);
}


2.获取javaBean的方法

//获取本类及父类public的方法
Method[] methods = class1.getMethods();
for(Method m:methods) {
System.out.println("***执行getMethods()方法");
System.out.println(m);
}
//获取本类当中所有的方法
Method[] methods2 = class1.getDeclaredMethods();
for(Method m:methods2) {
System.out.println("***执行getDeclaredMthods()方法***");
System.out.println(m);
}


3.通过反射进行Bean与Bean之间的转换

/**
* 实体类之间转换
* @param source:源类
* @param target:要转换的目标类
* @return
*/
public static Object convertBean(Object source,Object target) {
//获取来源类的所有方法
Method[] sourceMethods = source.getClass().getDeclaredMethods();
//要转换目标类的所有方法
Method[] targetMethods = target.getClass().getDeclaredMethods();
//遍历源类的所有方法
for(Method sm:sourceMethods) {
//取源类的方法名称
String sourceMethodName = sm.getName();
//以get开头的方法
if(sourceMethodName.startsWith("get")) {
try {
Object value = sm.invoke(source);
for(Method tm:targetMethods) {
String targetMethodName = tm.getName();
if(targetMethodName.startsWith("set") && (sourceMethodName.substring(3, sourceMethodName.length()).equals(targetMethodName.substring(3,targetMethodName.length())))) {
tm.invoke(target, value);
}
}
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
return target;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: