Java class object from type variable

Is there a way to get Class object from the type variable in Java generic class? Something like that:

public class Bar extends Foo<T> {
    public Class getParameterClass() {
        return T.class; // doesn't compile
    }
}

This type information is available at compile time and therefore should not be affected by type erasure, so, theoretically, there should be a way to accomplish this. Does it exist?

Answers


This works:

public static class Bar extends Foo<String> {
  public Class<?> getParameterClass() {
    return (Class<?>) (((ParameterizedType)Bar.class.getGenericSuperclass()).getActualTypeArguments()[0]);
  }
}

The code snippet is a bit confusing. Is T a type parameter or a class?

public static class Bar extends Foo<String> {
    public Class<?> getParameterClass() {
        return (Class<?>) (((ParameterizedType)Bar.class.getGenericSuperclass()).getActualTypeArguments()[0]);
    }
}

public static class Bar2<T> extends Foo<T> {
    public Class<?> getParameterClass() {
        return (Class<?>) (((ParameterizedType)Bar2.class.getGenericSuperclass()).getActualTypeArguments()[0]);
    }
}


public static void main(String[] args) {
    System.out.println(new Bar().getParameterClass());
    System.out.println(new Bar2<Object>().getParameterClass());
}

Actually the second println will cause an exception.


This code works for derived classes as well:

import java.lang.reflect.ParameterizedType;

public abstract class A<B> 
{
    public Class<B> getClassOfB() throws Exception 
    {
        ParameterizedType superclass = (ParameterizedType) getClass().getGenericSuperclass();

        return (Class<B>) superclass.getActualTypeArguments()[0];
    }
}

snagged from here: https://stackoverflow.com/a/4699117/26510


Need Your Help

Using comparison operators in SELECT clause of T-SQL query

sql sql-server sql-server-2008 tsql comparison-operators

How to select a result of comparison operator as a field with type BIT?

How to intercept any postback in a page? - ASP.NET

c# asp.net postback

I want to intercept any postbacks in the current page BEFORE it occurs . I want to do some custom manipulation before a postback is served. Any ideas how to do that?