如何创建一个类<! - ?从字符串扩展XYZ - >

时间:2018-01-16 16:17:25

标签: java

我正在尝试从字符串创建一个类,但希望是特定类型,如:

Class<? extends XYZ> aa = Class.forName(messageType);

private ResponseMessage processScore(Map<String, Object> result) {
    Optional<String> messageType = result.keySet().stream().findAny();
    Class<? extends State> aa = Class.forName(messageType.get());
    return messageType.map(messageKey -> extractScore(result.get(messageKey), messageKey, aa)).orElse(null);
}

在java中可以吗?

由于

2 个答案:

答案 0 :(得分:3)

你想要asSubclass method of Class

Class<?> unknownClass = Class.forName(string);
Class<? extends State> stateSubClass = unknownClass.asSubclass(State.class);

答案 1 :(得分:2)

如果您通过Class.forName(fqcn)成功查找课程,则可能需要检查是否可以将其分配给State,即State本身或子类。然后你需要显式转换为Class<? extends State>告诉编译器这是可以的:

Class<?> lookedUp= Class.forName( messageType.get() );

//check the class actually is State or a subclass
if( State.class.isAssignableFrom( lookedUp ) ) {
  //explicit cast needed 
  //Class<? extends State> aa = (Class<? extends State>)lookedUp;

  //as per correct comment by Daniel Pryden use asSubclass(BaseClass)
  Class<? extends State> aa = lookedUp.asSubclass(State.class);

  //use aa
}