有没有办法避免从Object类继承的方法.我有以下代码:
public void testGetMethods() {
SomeClass sc = new SomeClass();
Class c = sc.getClass();
Method [] methods = c.getMethods();
for (Method method : methods) {
System.out.println(method.getName());
}
}
Run Code Online (Sandbox Code Playgroud)
一切都还可以,但它也返回Object类中的方法,如hashCode,getClass,notify,equals等.类SomeClass应该只有两个自己的方法,即m1和m2.
我只想打印这些方法(m1,m2).有什么办法可以实现吗?
rge*_*man 11
使用Class
类的getDeclaredMethods()
方法.
返回一个Method对象数组,这些对象反映由此Class对象表示的类或接口声明的所有方法.这包括公共,受保护,默认(包)访问和私有方法,但不包括继承的方法.
Method[] declaredMethods = c.getDeclaredMethods();
Run Code Online (Sandbox Code Playgroud)