梦书之家(移动开发)

你有一个苹果,我有一个苹果,我们交换一下,一人还是一个苹果;你有一个思想,我有一个思想,我们交换一下,一人就有两个思想。 ——肖伯纳

导航

通过反射获取类的所有构造函数与方法

构造函数:

Class<?> sp = Class.forName("java.lang.String");
Pattern p = Pattern.compile("\\w+\\.");
Constructor<?>[] ctors = sp.getDeclaredConstructors();
for(Constructor<?> ctor : ctors){
    System.out.println(p.matcher(ctor.toString()).replaceAll(""));
}

其中 Pattern对象p是为了去除类的完整名字,比如"java.lang.String"中的“java.“与“lang.“, 下同 。

 

方法:

Class<?> sp = Class.forName("java.lang.String");
Pattern p = Pattern.compile("\\w+\\.");
Method[] methods = sp.getDeclaredMethods();
for(Method method : methods){
    System.out.println(p.matcher(method.toString()).replaceAll(""));
}

 

需要注意的是:不管是通过getDeclaredField还是getField都只能获取到该类本身添加的属性,而不能

获取到其父类的属性,需要自己通过父类的名字以及传递该类对象来获取实例的属性。

 

posted on 2012-07-16 17:03  梦书  阅读(1771)  评论(0编辑  收藏  举报