Get the name of a generic class in a java interface

2

I have the following case:

public interface CustomRepository<T> {
...
}

public class CustomRepositoryImpl<T> implements CustomRepository<T>{
//Como puedo obtener el nombre de la Clase T
}

//Por ejemplo si uso la clase Usuario, deberia obtener el nombre usuario
public interface UsuarioRepository extends CustomRepository<Usuario>{

}
    
asked by Andrés Pedro Gonzales Rojas 29.03.2018 в 23:21
source

1 answer

3

You can not see it directly because the compiler removes the types once compiled, the one called borrado de tipo .

However you can pass it to the constructor when you create it, so save the type of class to be able to use it afterwards. An example:

public class CustomRepositoryImpl<T> implements CustomRepository<T>{

    private Class<T> type; // Variable con el tipo

    // Guardamos el tipo que le pasamos en el constructor
    public CustomRepositoryImpl(Class<T> type){
        this.type = type;
    }

    // Clase que devuelve un string del tipo
    public String getClassName(){
        return this.type.getCanonicalName();
    }
}

So, for example, if we create it with the String type:

CustomRepositoryImpl<String> test = new CustomRepositoryImpl<String>(String.class);

Calling test.getClassName() will return java.lang.String

    
answered by 30.03.2018 в 00:06