![](/img/trans.png)
[英]Misunderstanding of class of returned instance from generic method of class called from subclass instance in Java
[英]Method for generic creating of Instance from sub class in java
我有一个抽象超类:
class abstract Father{
public static boolean controll(){here comes code....}
}
class child1 extends Father{
public static boolean controll(){
does something....
Father.controll();
}}
在我的主要班上,我会像这样培养孩子
if(Child1.controll()){ new Child1().callingOtherMethod()}
if(Child2.controll()){ new Child2().callingOtherMethod()}
等等多次...
我对泛型仍然很陌生,并不了解它。 如何在我的主类中编写更通用的方法,该方法类似于:
public void moveToStep(Class<? extends Father> clasz){
if(clasz.controll())
new clasz().callingOtherMethod() }
所以我可以简称为:
moveToStep(Child1.class); moveToStep(Child1.class); ...
尝试使用泛型可能是错误的。 不确定在主类中避免所有这些重复的正确方法是什么
您要查找的代码在java.lang.reflect中。 您可以尝试使用
http://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#newInstance--
这仅在存在空构造函数的情况下起作用。 否则,您将需要使用反射来查找构造函数,以找出要传入的值。
首先,将要抽象调用的方法包括在超类中。
abstract class Father {
public static boolean predicate() { /*...*/ }
protected abstract void method();
}
然后,确保您的子类包含一个空的构造函数。
final class Child1 extends Father {
Child1() { /*...*/ }
public static boolean predicate() { return true; }
@Override
public void method() {
System.out.println("Child1");
}
}
看看Class
和Method
的文档。 使用反射调用谓词(在您的示例中为controll
),然后使用newInstance
实例化一个类并调用另一个方法。
public static void main(String[] args) {
List<Class<? extends Father>> children =
Arrays.asList(Child1.class, Child2.class);
for (Class<? extends Father> c: children) {
try {
Method pred = c.getDeclaredMethod("predicate");
Boolean b = (Boolean) pred.invoke(null);
if (b.booleanValue()) {
Father f = (Father) c.newInstance();
f.method();
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.