我有一个这样的父类(super class),它有一个工厂方法:
@DiscriminatorColumn(
name = "etype",
discriminatorType = DiscriminatorType.STRING
)
public abstract class ChallengeReward {
public static ChallengeReward createFromFactory(String rewardType){
ChallengeRewardType type = ChallengeReward.fromString(rewardType);
ChallengeReward challengeReward = null;
switch(type){
case point:
challengeReward = new PointChallengeReward();
break;
case notification:
challengeReward = new NotificationChallengeReward();
break;
case item:
challengeReward = new ItemChallengeReward();
break;
}
return challengeReward;
}
public String getClientId(){
return "ABCDEF";
}
}
和子类本身没有构造函数。因此,所有挑战奖励都位于同一个表中,表中有一个名为“etype”的鉴别器列。
现在的问题是我想反射性地调用方法 getClientId(),但我无法实例化 ChallengeReward,因为它是抽象的。所以我需要实例化它的子类之一,但我不能执行 subclass.newInstance()。
我有哪些选择?
编辑 1: 抱歉,我的问题不是很清楚。问题是我正在编写一个通用的 servlet,它将遍历包中的所有类,因此需要反射。虽然该方法实际上是静态的,但我不知道如何静态调用它,因为我只知道运行时的当前类。
编辑 2: 原来可以调用method.invoke(null)调用静态方法,谢谢madth3
最佳答案
我认为您可以通过使用类名本身来获取方法
,然后如下调用该方法:
String clientId = null;
Class challengeRewardClass =Class.forName(ChallengeReward.class.getName());
Method[] methods = challengeRewardClass.getMethods();
for(Method method: methods){
if(method.getName().equals("getClientId")){
clientId = method.invoke(objectoToBeUsedForMethodCall, null);
}
}
关于java - 实例化抽象父类(super class)的子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13055743/