简体   繁体   中英

Create instance of generic type in Java when parameterized type is contained?

This is a follow-up to my question:

Create instance of generic type in Java when parameterized type passes through hierarchies?

For attempting to create a new generic from a contained class, I tried to adapt Steve B's approach of creating an anonymous subclass:

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class ParameterizedTypeEg {
    ParameterizedTypeEg () {
        ContainsParameterized<String> containString = new ContainsParameterized<String>();
    }
    public class Parameterized<E> {
        Parameterized () {
        }
        public Class<E> getTypeParameterClass() {
            Type type = getClass().getGenericSuperclass();
            ParameterizedType paramType = (ParameterizedType) type;
            return (Class<E>) paramType.getActualTypeArguments()[0];
        }
        public Constructor<E> getTypeParameterConstructor() {
            Constructor<E> constructor = null;
            try {
                constructor = getTypeParameterClass().getConstructor(QueriedColor.class);
            } catch (NoSuchMethodException e) { System.err.println(e); }
            return constructor;
        }           
    }
    class ContainsParameterized<E> {
        ContainsParameterized () {
            Parameterized<E> contained = new Parameterized<E>(){};
            try {
                E element = contained.getTypeParameterConstructor().newInstance();
            }
            catch (InstantiationException e) { System.err.println(e); }
            catch (IllegalAccessException e) { System.err.println(e); }
            catch (InvocationTargetException e) { System.err.println(e); }
        }
    }
    public static void main(String[] args) {
        new ParameterizedTypeEg();
    }
}

Please note the line Parameterized contained = new Parameterized(){};

Here I am attempting to create the anonymous subclass, as suggested by Steve B in the other post. However, I get a ClassCastException in the getTypeParameterClass() method. This is the same type of exception as in my other posting. That lead me to think that I could use the same solution as Steve B suggested for that problem.

The anonymous class must have the actual type parameter hard-coded in its declaration for it to work.

new Parameterized<E>(){};

does not work. You are just hard-coding "E" (a type variable). So when you look at the metadata using reflection all you see is "E" (a type variable).

You must create a subclass which hard-codes its superclass with an actual class as type argument at compile-time:

new Parameterized<String>(){};

I tried to adapt Steve B's approach of creating an anonymous subclass:

You missed the whole point of that. The point was not to create a subclass. The point was to create a subclass with the actual class of the type argument hard-coded in the superclass .

What you're trying to do can work so long as E is parameterized in a type definition somewhere. For example:

Parameterized<E> pe = new Parameterized<E>();

This will not allow you to resolve E since it's not part of a type definition. On the otherhand, this:

class StringE extends Parameterized<String> {}

or this:

Parameterized<String> ps = new Parameterized<String>(){};

will work since we're specifying the value of E as part of a type definition. To resolve the value of E , you might use TypeTools :

Class<?> stringType = TypeResolver.resolveRawArgument(Parameterized.class, ps.getClass());
assert stringType == String.class;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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