今天,在编写代码时,我开始深入研究反射的世界。我以前曾零零碎碎地弄乱了它,但从未达到过这个程度,无论我在哪里看,我都找不到对我问题的答案,所以我在这里!当前,我正在尝试对类的构造函数请求参数使用反射,但是为了易于使用,我希望使用参数的超类。
以下是引起问题的代码并提供了一些解释:
this.listener = (MyListener) listenerClass.getConstructor(MyAppState.class).newInstance(this);
关键是MyAppState是我所有appstate都从其扩展的类,并且每个侦听器都采用其自己的特定AppState,该AppState扩展了MyAppState但具有彼此不同的其他功能。我需要知道的是,我可以在.getConstructor()中放入什么来指定要传递的类是其所需参数的超类。
这是代码的理论示例:
this.listener = (MyListener) listenerClass.getConstructor(Class extends MyAppState.class).newInstance(this);
所以这是可能的,还是我应该只使用我的代码来使第二个构造函数接受MyAppState类,或者其他类似的东西。
另外,很抱歉,如果这不是主题,但为了防止将来出现问题,我被告知这个问题是主观的。有什么方法可以使将来的问题措辞不那么主观,或者该方法是否可以判断问题是否是主观的呢?
[编辑]根据要求,还有其他一些与该问题有关的示例:
public MyAppState(Node screen, Class listenerClass)
{
this.screen = screen;
try
{
this.listener = (MyListener) listenerClass.getConstructor(MyAppState.class).newInstance(this);
}
catch (Exception e)
{
Logger.getLogger(MyAppState.class.getName()).log(Level.SEVERE, "The listener for the {0} appstate could not be created using reflection.", new Object[]{this.getClass().getName()});
System.exit(-1);
}
}
上面是完整的父类的构造函数,该类扩展了一个类,但不包含构造函数,因此我不确定是否需要它。如果是这样,请随时提出要求。
public class OptionsMenuState extends MyAppState
{
public OptionsMenuState()
{
super(new Node("Options Screen"), OptionsMenuStateListener.class);
}
那是一个类,它的构造函数被截短以使其简短。
public class MainMenuState extends MyAppState
{
public MainMenuState()
{
super(new Node("Start Screen"), MainMenuStateListener.class);
}
这是另一个类及其构造函数。
[编辑]按照建议,我创建了一个程序,该程序大致模仿了我要尝试执行的操作。
/ *打包任何东西; //不要放置包名称! * /
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
//This is what I want to do but I don't know how to have java allow me to pass in Greeting.
createObject(SimpleSentence.class);
createObject(DifferentSentence.class);
}
public static void createObject(Class theClass)
{
theClass.getConstructor(Greeting.class).newInstance(new Hello());
}
class SimpleSentence
{
Hello firstWord;
public SimpleSentence(Hello word)
{
firstWord = word;
}
}
class DifferentSentence
{
Howdy firstWord;
public DifferentSentence(Howdy word)
{
firstWord = word;
}
}
class Greeting
{
}
class Hello extends Greeting
{
}
class Howdy extends Greeting
{
}
}
最佳答案
简短的答案是你不能。 getConstructor(Class<?>...parametertypes)
是非常明确的,因为它只需要精确地匹配零或一个构造函数。
您将需要遍历所有构造函数以找到一个具有可从MyAppState
分配的参数的构造函数
例如大纲:
final Constructor<?>[] ctrs = listenerClass.getConstructors();
for (Constructor<?> constructor : ctrs) {
if (constructor.getParameterTypes()[0].isAssignableFrom(MyAppState.class)) {
// use this one?
}
}
关于java - 如何使用反射获取将父类(super class)作为参数传递给的构造函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24545654/