Java.lang.reflect 包下常用的类及方法简介

Class类之主要方法简介
Class<?> cls = String.class;
一)类自身的信息
1. 包路径 cls.getPackage();
2. 类名 cls.getName();cls.getSimpleName();
3. 类修饰符 cls.getModifiers();
4. 类属性 cls.getFields();cls.getDeclaredFields();
5. 类方法 cls.getMethods();cls.getDeclaredMethods();
6. 类构造器 cls.getConstructors();
7. 标注信息 cls.getAnnotations();
8. 是否为基本类型数据 cls.isPrimitive();
9. 获得系统类的 getClassLoader(); 这个也较为常用,加载类的时候

获取资源信息

获取方法:
1.object.getClass().getDeclaredMethods() : 会方式所有定义的 public, protected, default private访问权限的方法,但是不会取父类的方法或继承之父类的方法
2.object.getClass().getMethods():会取得所有自身类及父类中所有定义的方法

从上面我们可以看出,一般在对于方法的操作我更多是采用第一个方法,做一些属性的COPY,或是方法的调用!较少用到第二个方法!

同理 getFields() && getDeclaredFields() 也是一样的原理.

二)获取资源的信息

cls.getResource(“http://xx/xx”);
cls.getResourceAsStream(“xx.properties”);

判断一个方法的修饰符
Modifier.isPublic(method.getModifiers());
Modifier.isAbstract(method.getModifiers());
Modifier.isInterface(method.getModifiers());
Modifier.isFinal(method.getModifiers());
Modifier.isNative(method.getModifiers());
Modifier.isPrivate(method.getModifiers());

那么在Class类操作过程中产生的Field Method 都可以通过这getModifiers()配合Modifier来得到属性或是方法的修饰符
Field :
1.获得修饰符 field.getModifiers();
2.获取基本的类型的值
field.getBoolean(obj);
field.getInt(obj);
field.getDouble(obj);
……
3.获得在属性中的标注 这个特性在1.5版本以后添加,CLASS,METHOD,FIELD 都存在 field.getAnnotations();

Method :
1.返回类型 method.getReturnType();
2.参数类型 method.getParameterTypes();
3.名字 method.getName();
4.修饰符 method.getModifiers();
5.标注 method.getAnnotations();
6.反射调用方法 method.invoke(obj, args);也是最为关键的一个方法

根据上面的这些方法,简单造了一个BeanUtils中对象属性COPY的轮子

package com.inter12.test.myclass;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
* TODO Comment of MyBeanUtil
*
* @author inter12
*/
public class MyBeanUtil {

private static final String SET = “set”;
private static final String IS = “is”;
private static final String GET = “get”;

public Object beanCopy(Object sourceObject, Class<?> targetClass) throws IllegalArgumentException,
IllegalAccessException, InvocationTargetException,
InstantiationException {

// 将目标对象的所有SET方法组转成 name-method 的MAP
Map<String, Method> targetMethodMap = getTargetMethodMap(targetClass);

Object targetObject = targetClass.newInstance();

Method[] sourceMethods = sourceObject.getClass().getDeclaredMethods();
for (Method m : sourceMethods) {

// 要求时PUBLIC 且无参的方法
if (Modifier.isPublic(m.getModifiers()) && m.getParameterTypes().length == 0) {

// 根据源对象中的get方法,匹配目标对象中是否存在对应的SET方法之,若是无返回NULL
String methodName = getMethodName(m);

if (targetMethodMap.containsKey(methodName)) {

// 源对象的值
Object sourceValue = m.invoke(sourceObject, (Object[]) null);

// 设置到目标对象
Method targetMethod = targetMethodMap.get(methodName);
targetMethod.invoke(targetObject, new Object[] { sourceValue });
}
}
}

return targetObject;
}

private String getMethodName(Method m) {
String methodName = null;
if (m.getName().startsWith(GET)) {
methodName = SET + m.getName().substring(3, m.getName().length());

} else if (m.getName().startsWith(IS)) {
methodName = SET + m.getName().substring(2, m.getName().length());
}
return methodName;
}

private Map<String, Method> getTargetMethodMap(Class<?> targetClass) {

Map<String, Method> methodMap = new HashMap<String, Method>();

Method[] targetMethods = targetClass.getDeclaredMethods();
if (null != targetClass && 0 != targetMethods.length) {
for (Method method : targetMethods) {

if (method.getName().startsWith(SET)) {
methodMap.put(method.getName(), method);
}
}
}
return methodMap;
}

public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException, InstantiationException {

Student student = new Student(“xzm”, true, 27, new Address(“hz”));
student.setBirthDay(new Date(2011, 11, 1));

MyBeanUtil myBeanUtil = new MyBeanUtil();

Object beanCopy = myBeanUtil.beanCopy(student, BakStudent.class);

System.out.println(beanCopy.toString());
}
}

发表评论?

0 条评论。

发表评论


注意 - 你可以用以下 HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>