Java反射从类名获取构造函数失败 [英] Java reflection get constructor from class name failed
问题描述
我有以下代码段:
class You{
public You(String s){}
}
public static void main(String[] args) throws NoSuchMethodException {
Constructor[] constructors = You.class.getConstructors();
for(Constructor constructor: constructors){
Class[] parameterTypes = constructor.getParameterTypes();
for(Class c: parameterTypes){
System.out.println(c.getName());//print java.lang.String
}
}
Constructor constructor =
You.class.getConstructor(String.class);//NoSuchMethodException?
}
这很老了,当我打印构造函数时,它有一个 java.lang.String
作为参数。但是,当我尝试 You.class.getConstructor
时,它说没有以 String.class
作为参数的构造函数。
This is quite old, when I print the constructors, it has one constructor with java.lang.String
as parameter. But when I tried to You.class.getConstructor
it says no constructor with String.class
as parameter.
我在Mac上使用 java1.8 。
非常感谢。
推荐答案
如果不是这种情况,我将删除此答案,但看起来您
是一个内部类,并且我怀疑您的实际代码如下所示:
I'll delete this answer if it's not the case, but it looks like You
is an inner class, and I suspect your actual code looks something like this:
public class Foo {
class You {
public You(String s){}
}
public static void main(String[] args) throws NoSuchMethodException {
Constructor[] constructors = You.class.getConstructors();
for (Constructor constructor: constructors) {
Class[] parameterTypes = constructor.getParameterTypes();
for (Class c: parameterTypes){
System.out.println(c.getName());//print java.lang.String
}
}
Constructor constructor =
You.class.getConstructor(String.class);//NoSuchMethodException?
}
}
来自文档 $ c> Class#getConstructor :
From the documentation of Class#getConstructor
:
如果此Class对象表示在非静态中声明的内部类在上下文中,形式参数类型包括显式的封闭实例作为第一个参数。
If this Class object represents an inner class declared in a non-static context, the formal parameter types include the explicit enclosing instance as the first parameter.
因此,您必须使用
Constructor constructor = You.class.getConstructor(Foo.class, String.class);
但显然将 Foo
替换为您的封闭课程。
But obviously replace Foo
with the name of your enclosing class.
这篇关于Java反射从类名获取构造函数失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!