1

I was going throught this link

Java Generic Class - Determine Type

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 printh output as 1 but it prints 2. Please help me in understanding this. Thanks.

Community
  • 1
  • 1
LPD
  • 2,833
  • 2
  • 29
  • 48

2 Answers2

3

A trick that actually works is used in the google guice's TypeLiteral. In the constructor of a subclass of a generic class, you do have access to the parent's generic "instantiation", even at runtime... because the generic type information has been retained for inheritance purposes at compile-time. Example usage:

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 subclass-of-a-generic, due to type erasure; and is probably overkill for most applications.

tucuxi
  • 17,561
  • 2
  • 43
  • 74
1

Clazz would be T in this case.

Generics are considered only at compile time in java. You can attempt to determine the value of the type parameter of a collection at runtime by looking at its members' classes(without 100% certainty, you can end up with a subclass...). There is no way to determine the type parameter value of an empty collection at runtime.

  • 1
    True in the general case, but false when class hierarchies are involved - see my answer above :-) – tucuxi Sep 04 '13 at 09:55