Pasha
Pasha

Reputation: 175

Get the name of the Generic (T in <T extends... >) in java

I have a this class and method:

public class Runner<T extends Domain> implements Runnable {

public void run() {
   ...
    Runtime.getRuntime().exec(...)
   ...
}

I need to execute the file and pass it the type of T as an agument (or some other string that will allow me to distinguish between diferent domains in the executed file, but T is a class that extends the class Domain, where Domain is an abstract class.

I thought about adding a static method that returns the name of the class and calling T.getName();, but this can not be done in abstract classes..

How should I do it?

Thanks!

Upvotes: 0

Views: 133

Answers (3)

Dmitry Ginzburg
Dmitry Ginzburg

Reputation: 7461

You can create the constructor for your class, in which you can pass the Class object and the use it:

private Class<T> clazz;

public Runner(Class<T> clazz) {
    this.clazz = clazz;
}

// ...

public void runFile() {
    // do smth with
    clazz.getName()
}

Upvotes: 2

blacktide
blacktide

Reputation: 12086

Pass the type into the constructor of the class:

public class Runner<T extends Domain> implements Runnable {

    private Class<T> clazz;

    public Runner(Class<T> clazz) {
        this.clazz = clazz;
    }

    public void run() {
        // Use your class here
        String name = clazz.getName();
    }
}

Upvotes: 2

frIT
frIT

Reputation: 3285

private void runFile(Class<T> classOfT) {...}

Upvotes: 0

Related Questions