Java反射经典实例 Java Reflection Cookbook(二)

2014-11-24 00:38:51 · 作者: · 浏览: 1
ect.Field;
import java.lang.reflect.Method;


/**
* Java Reflection Cookbook
*
* @author Michael Lee
* @since 2006-8-23
* @version 0.1a
*/

public class Reflection {
/**
* 得到某个对象的公共属性
*
* @param owner, fieldName
* @return 该属性对象
* @throws Exception
*
*/
public Object getProperty(Object owner, String fieldName) throws Exception {
Class ownerClass = owner.getClass();

Field field = ownerClass.getField(fieldName);

Object property = field.get(owner);

return property;
}

/**
* 得到某类的静态公共属性
*
* @param className 类名
* @param fieldName 属性名
* @return 该属性对象
* @throws Exception
*/
public Object getStaticProperty(String className, String fieldName)
throws Exception {
Class ownerClass = Class.forName(className);

Field field = ownerClass.getField(fieldName);

Object property = field.get(ownerClass);

return property;
}


/**
* 执行某对象方法
*
* @param owner
* 对象
* @param methodName
* 方法名
* @param args
* 参数
* @return 方法返回值
* @throws Exception
*/
public Object invokeMethod(Object own