【发布时间】:2015-01-28 10:29:36
【问题描述】:
所以我在 jdk 7 上运行了这两个类:
abstract class Aclass
{
public void foo()
{
}
public void bar()
{
}
}
还有:
public class Bclass extends Aclass
{
public void foo(Integer one)
{
}
public void bar(String two)
{
}
}
我的目标是加载 Bclass,并且只加载 Bclass,打印出其声明的方法和那些声明的方法的参数。 这是我使用的代码:
public static void main(String[] args)
{
try
{
Class<?> clazz = Tester.class.getClassLoader().loadClass("full_path.Bclass");
for (Method method : clazz.getDeclaredMethods())
{
System.out.println("Method name: " + method.getName() + " From class: " + method.getDeclaringClass().getCanonicalName() + " with declared methods:");// test
for (Class<?> param : method.getParameterTypes())
{
System.out.println(param.getCanonicalName());
}
}
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
运行此代码会产生以下输出:
Method name: foo From class: complete_path.Bclass with declared methods:
Method name: foo From class: complete_path.Bclass with declared methods:
java.lang.Integer
Method name: bar From class: complete_path.Bclass with declared methods:
Method name: bar From class: complete_path.Bclass with declared methods:
java.lang.String
但在方法 [getDeclaredMethods()] 的 javadoc 中,我看到 but excludes inherited methods ,根据我的测试,这似乎不是这种情况,该方法显然会在重载时加载继承的方法。
还是我做错了什么?
【问题讨论】:
-
getDeclaredMethiods()的 Javadoc 声明它“排除了继承的方法”。因此,您声称获得的输出是不可能的。我注意到您发布的代码的格式不正确,这很奇怪。大概您没有运行您认为正在运行的代码。也许你叫getMethods()而不是getDeclaredMethods()。 -
嗨,不,这是我正在运行的确切代码,我唯一编辑的是用
complete_path.替换类的输出的完整路径,因为它暴露了太多信息。顺便说一句,你自己试过吗? -
@JBoy,我在 Java 8 上试过,但输出不同。我只得到
getDeclaredMethods()JavaDoc 中定义的子类方法。你确定这是一个完整的例子吗? -
@EJP 我尝试了相同的代码,但在 java 1.7 上出现了这种情况。显然在 java 8 和 1.5 上(进一步阅读有人尝试过),实现不同。
-
@wassgren 显然这只发生在 java 7 上
标签: java reflection methods