Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the class of a Java generic, and interface implementation of generics

Tags:

java

generics

I'd like to make a class that looks basically like this:

public class MyClass<T implements Serializable) {

   void function() {
      Class c = T.class;
   }
}

Two errors:
- I cannot call T.class, even though I can do that with any other object type
- I cannot enforce that T implements Serializable in this way

How do I solve my two generics problems?

Cheers

Nik

like image 246
niklassaers Avatar asked Aug 24 '09 07:08

niklassaers


1 Answers

You can't get the type.

Generics are implemented using something called type-erasure.

When a generic type is instantiated, the compiler translates those types by a technique called type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method. Type erasure enables Java applications that use generics to maintain binary compatibility with Java libraries and applications that were created before generics.

The essence of this is that the type information is used by the compiler and discarded, hence not available at runtime.

With regards to the enforcing T implements Serializable, you just need the following:

public class MyClass<T extends Serializable>)
{
  public void function(T obj) 
  {
    ...
  }
}

This is simply referring to the is a relationship, so an class that implements Serializable, is a Serializable and can be passed to function.

like image 180
Nick Holt Avatar answered Oct 29 '22 20:10

Nick Holt