Using a Parameterized Type for Type Inference

I followed this link

Java Generic Class - type inference

I tried with this program.

package my;

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

public class GenericTypeIdentification {

    public static void main( String args[] ) {
        Node<Integer> obj = new GenericTypeIdentification().new SubNode<Integer>( 1 );
        ParameterizedType parameterizedType = ( ParameterizedType ) obj.getClass().getGenericSuperclass();
        Type clazz = parameterizedType.getActualTypeArguments()[0];
        if ( clazz == Integer.class ) {
            System.out.println( 1 );
        }
        else {
            System.out.println( 2 );
        }
    }

    class Node<T> {

        private final T value;

        public Node( T val ) {
            this.value = val;
        }

        public T evaluate() {
            return value;
        };

    }

    class SubNode<T> extends Node<T> {

        private final T value;

        public SubNode( T val ) {
            super( val );
            value = val;
        }

        @Override
        public T evaluate() {
            return value;
        };
    }
}

      

My understanding was that it should neglect the output 1

, but it prints 2

. Please help me understand this. Thank.

+1


source to share


2 answers


The trick that actually works is the google guice TypeLiteral used . In the constructor of a subclass of a generic class, you have access to the parent generic "instance" even at runtime ... because the generic type information was retained for inheritance purposes at compile time. Usage example:

TypeLiteral<MyClass> test = new TypeLiteral<MyClass>() {}; // notice the {} to build an anon. subclass
System.err.println(test.getType()); // outputs "MyClass"

      



This does not work without using a generic subclass due to type erasure; and probably too much for most applications.

+3


source


In this case, Clazz would be T.



Generics are only considered at compile time in java. You can try to determine the value of the collection type parameter at runtime by looking at the classes of its members (without 100% certainty, you can subclass ...). Cannot determine the value of an empty collection type parameter at run time.

+1


source







All Articles