Abdullah
Abdullah

Reputation: 637

How can i get Class from Generic Type

I do not know how I will explain, I have a class something like

public class MyClass<T>{
    private Class <?> type;
    public MyClass(string className){
        this.type = Class.forName(className);
        Field[] fields = type.getDeclaredFields();//why i need type
    }
}

Then i create an object of that class:

MyClass<Person> persons = new MyClass<>("packageName.Person");

Is there anyway to do this like

MyClass<Person> persons = new MyClass<>();

Upvotes: 1

Views: 154

Answers (1)

Kayaman
Kayaman

Reputation: 73558

You can't because of the way generics are implemented in Java. You can often see a Class<T> clazz parameter being passed to work around it.

In fact, it doesn't make sense for you to pass in a String. Pass in Person.class instead, so you won't need the Class.forName().

Upvotes: 4

Related Questions