简体   繁体   English

Java 和类型擦除 - 如何从字符串“MyClass”生成 MyClass.class

[英]Java & Type Erasure - How to generify MyClass.class from the string "MyClass"

So I have a parameterized handler type where the type is a subclass of MessageBase .所以我有一个参数化处理程序类型,其中类型是MessageBase的子类。

public class ResponseHandler<T extends MessageBase> {

    private final T message;

    private ResponseHandler(final Class<T> clazz) {
        this.message = get(clazz);
    }

    public static <T extends MessageBase> ResponseHandler<T> of(Class<T> clazz) {
        return new ResponseHandler<>(clazz);
    }

    private T get(Class<T> clazz) {
        ...
    }
}

I also have a subset of DerivedMessage classes like DerivedMessage1 and DerivedMessage2 which both extend MessageBase .我还有一个DerivedMessage类的子集,例如DerivedMessage1DerivedMessage2 ,它们都扩展了MessageBase I want to be able to create the right ResponseHandler based on a string of the class name like this:我希望能够基于 class 名称的字符串创建正确的ResponseHandler ,如下所示:

// defined some String s;
if (s == "com.package.DerivedMessage1") {
    ResponseHandler<DerivedMessage1> h1 = ResponseHandler.of(DerivedMessage1.class);
    // do something with h1
} else if (s == "com.package.DerivedMessage2") {
    ResponseHandler<DerivedMessage2> h2 = ResponseHandler.of(DerivedMessage2.class);
    // do something with h2
}

But I'm wondering if there's a way to do this generically for all DerivedMessage classes, which derive from MessageBase .但我想知道是否有一种方法可以对所有派生自MessageBaseDerivedMessage类进行通用处理。 I haven't found a way to do the DerivedMessage1.class from a string like "com.package.DerivedMessage1".我还没有找到从“com.package.DerivedMessage1”之类的字符串执行DerivedMessage1.class的方法。 I've tried Class.forName(string) , but it returns a weird capture?我试过Class.forName(string) ,但它返回一个奇怪的capture? type that confuses me.让我感到困惑的类型。 Is there a way to accomplish this, or do I have to stick to the if statements?有没有办法做到这一点,还是我必须坚持 if 语句?

you can use getCanonicalName() .您可以使用getCanonicalName()

For example: DerivedMessage1.class.getCanonicalName() returns "com.package.DerivedMessage1"例如: DerivedMessage1.class.getCanonicalName()返回"com.package.DerivedMessage1"

so the conditions becomes所以条件变成了

if (DerivedMessage1.class. getCanonicalName().equals(s))) {
    ResponseHandler<DerivedMessage1> h1 = ResponseHandler.of(DerivedMessage1.class);
    // do something with h1
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM