简体   繁体   English

Java泛型问题

[英]Java Generics Question

I have a class 我有一堂课

public abstract class FakeClass<T extends MyClass> {
    protected HashMap<Character, T> myMap;

    private void myMethod(){
        myMap.put('c', /*???? I need to instatiate something of type T here.*/)
    }
}

As you can see, I can't figure out how to instantiate something of type T. Is this possible? 如您所见,我不知道如何实例化类型T的东西。这可能吗? If so can someone point me in the right direction to do it? 如果可以,那么有人可以指出正确的方向吗?

Thanks! 谢谢!

This can only be done by passing some information about T to myMethod() . 这只能通过将有关T的一些信息传递给myMethod() One approach, described in this thread , is to pass a factory object for T . 此线程中描述的一种方法是传递T的工厂对象。 A special case of this, described in this thread , is to pass a Class<T> type argument to myMethod() , which can then use type.newInstance() to create a new T object using the default constructor. 此线程中描述的一种特殊情况是将Class<T> type参数传递给myMethod() ,然后可以使用type.newInstance()使用默认构造函数创建新的T对象。 (This will fail if T does not have a default constructor.) The Class object serves as the factory object for T . (如果T没有默认的构造函数,这将失败。) Class对象用作T的工厂对象。

The reason we need all this is due to type erasure in Java. 我们需要所有这些的原因是由于Java中的类型擦除

Usually, the point of generics is to be able to accept an unknown-at-compile-time type as input. 通常,泛型的要点是能够接受编译时未知类型作为输入。

You can't instantiate an unknown class (because it might not have a visible constructor). 您无法实例化未知类(因为它可能没有可见的构造函数)。 If you just need a placeholder to put into the map, you can put a null value. 如果只需要在地图中放置一个占位符,则可以放置一个null值。

Without knowing more context, there isn't much more that anyone can do. 在不了解更多上下文的情况下,任何人都无法做更多的事情。

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

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