首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

关于反射的有关问题

2012-02-21 
关于反射的问题我现在有个方法名,譬如setName,以及一个类的class我想确定这个class是否能直接使用setNam

关于反射的问题
我现在有个方法名,譬如"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();


            if ( readMethod != null ) {
              readMethods.put( name, readMethod );
            }
            if ( writeMethod != null ) {
              writeMethods.put( name, writeMethod );
            }
            types.put( name, aType );
          }
        }
      }
    }
    catch (Exception e ) {
    }
  }
}



[解决办法]
简单点的是getMethods()这个方法,不过只能取到public的,protected的都取不到。
[解决办法]
递归查找,由于父类不太可能有很多层,所以问题也不大
[解决办法]
探讨
setAccessible(true);

[解决办法]
getMethods()能获得父类的方法,但只是public的,getDeclareMethods()可以获得所有方法但不包括父类的。
[解决办法]
getMethod(String name, Class<?>... parameterTypes)
遍历一个类的所有方法,无非要找到自己想要的那几个方法,不知道这个对LZ有用不?
[解决办法]
这样可能更通用些
Java code
package com.test;public class MyRegExp {    public static void main(String[] args){        boolean isExist=false;                try{            Class cls=Class.forName("com.test.SubClass");            Class[] properTypes={String.class};                Method[] methods=cls.getMethods();                        for(Method method:methods){                if(method.getName().equals("setName")){                    isExist=true;                    break;                }            }                    }catch(Exception e){                        e.printStackTrace();                    }                System.out.println(isExist);    }    }class SuperClass{    public void setName(){            }        public void setName1(String name){            }        public void setName2(String... names){            }}class SubClass extends SuperClass{    } 

热点排行