niklassaers niklassaers - 1 year ago 48
Java Question

Getting the class of a Java generic, and interface implementation of 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?



Answer Source

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.