日期:2014-05-20  浏览次数:20844 次

关于反射的问题
我现在有个方法名,譬如"setName",以及一个类的class

我想确定这个class是否能直接使用setName这个方法

我发现class.getDeclaredMethod()这个方法只能得到声明在这个类里的方法,而它继承来的方法得不到。

而class.getSuperclass()方法尽管能得到父类,但因为不知道这上面有多少层,所以显得很麻烦

有没有什么简单点的办法没?


------解决方案--------------------
如果你是取得所有满足javabean规范的属性的话,不应该这样操作。

下面是我以前用的一个以Map方式操作bean的类,你可以参考一下看看。
Java code
 
package util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class BeanMap{
private Object bean;
private Map <String,Method> readMethods;
private Map <String,Method> writeMethods;
private Map <String,Class <Object>> types;

public BeanMap(Object bean){
this.bean = bean;
initialise();
}

/**
* 为bean属性设置值
* @param name 属性名称
* @param value 属性值
* @throws Exception 当属性不存在或者属性类型不匹配时可能会抛出异常
*/
public void set(String name, Object value) throws Exception{
if(name.indexOf(".")>0){
Object obj = this.get(name.substring(0, name.indexOf(".")));
BeanMap bm = new BeanMap(obj);
bm.set(name.substring(name.indexOf(".")+1), value);
}else{
Class <Object> type = types.get(name);
Method method = writeMethods.get(name);
if(type==null || method==null){
throw new java.lang.NoSuchFieldException();
}
method.invoke(bean, value);
}
}

/**
* 取得bean的属性值
* @param name
* @return
* @throws Exception
*/
public Object get(String name) throws Exception{
if(name.indexOf(".")>0){
Object obj = this.get(name.substring(0, name.indexOf(".")));
BeanMap bm = new BeanMap(obj);
return bm.get(name.substring(name.indexOf(".")+1));
}else{
Class <Object> type = types.get(name);
Method method = readMethods.get(name);
if(type==null || method==null){
throw new java.lang.NoSuchFieldException();
}
return method.invoke(bean);
}
}

@SuppressWarnings("unchecked")
/**
* 为bean map进行初始化
*/
private void initialise()
  {
readMethods = new HashMap <String,Method>();
writeMethods = new HashMap <String,Method>();
types = new HashMap <String,Class <Object>>();
    if(bean == null) return;
    Class  beanClass = bean.getClass();
    try
    {
      BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
      PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
      if ( propertyDescriptors != null )
      {
        for ( int i = 0; i < propertyDescriptors.length; i++ )
        {
          PropertyDescriptor propertyDescriptor = propertyDescriptors[i];
          if ( propertyDescriptor != null )
          {
            String name = propertyDescriptor.getName();
            Method readMethod = propertyDescriptor.getReadMethod();
            Method writeMethod = propertyDescriptor.getWriteMethod();
            Class aType = propertyDescriptor.getPropertyType();