Create instance of generic type in Java?

后端 未结 27 3106
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-21 06:14

Is it possible to create an instance of a generic type in Java? I\'m thinking based on what I\'ve seen that the answer is no (due to type erasure), but

27条回答
  •  太阳男子
    2020-11-21 06:39

    I thought I could do that, but quite disappointed: it doesn't work, but I think it still worths sharing.

    Maybe someone can correct:

    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    
    interface SomeContainer {
        E createContents();
    }
    
    public class Main {
    
        @SuppressWarnings("unchecked")
        public static  SomeContainer createSomeContainer() {
            return (SomeContainer) Proxy.newProxyInstance(Main.class.getClassLoader(),
                    new Class[]{ SomeContainer.class }, new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    Class returnType = method.getReturnType();
                    return returnType.newInstance();
                }
            });
        }
    
        public static void main(String[] args) {
            SomeContainer container = createSomeContainer();
    
        [*] System.out.println("String created: [" +container.createContents()+"]");
    
        }
    }
    

    It produces:

    Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.String
        at Main.main(Main.java:26)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:601)
        at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
    

    Line 26 is the one with the [*].

    The only viable solution is the one by @JustinRudd

提交回复
热议问题