Phate
Phate

Reputation: 6612

Is it possible to pass a class type and use as return type?

I have a method which uses a parser, the parser call example is:

SpecificClass ret = parser.parse(getOutputStream(),SpecificClass.class);

note that the return type is THE SAME as the one specified as paramether.

Now, I'd like to create a method which does this call and returns the specific class type I want. For example:

public $$some construct I don't know$$ invokeParser(Class<?> c){
      //... operations....
      return parser.parse(getOutputStream(),c); //c works, I can pass it
}

Is it possible?

Upvotes: 3

Views: 74

Answers (1)

rgettman
rgettman

Reputation: 178263

You can make the method generic. Declare your type parameter with <T> and return a T.

public <T> T invokeParser(Class<T> c) {

Upvotes: 12

Related Questions