Generic return method

1

How do I make a method that returns a type entered in the parameters?

public <E> E to(E e)
{
    return (E)obj;
}

String st = to(String);
Integer it = to(Integer);

But this generates error, is there another way to do this?

    
asked by anonymous 04.04.2015 / 01:52

2 answers

4

This can be done using Class.cast :

public <E> E to(Class<E> e)
{
    return e.cast(obj);
}

Call it like this:

String st = to(String.class);
Integer it = to(Integer.class);

Example . Always remembering that your obj must be of a type compatible with the class used as an argument. It's also good to point out that this is an "insecure" operation, no more insecure than simply casting cast for the type you want:

public Object to() {
    return obj;
}

...

String st = (String)to();
Integer it = (Integer)to();

So in this case I do not see much advantage in this, but someone with more experience in Java may know some more practical use case for this Class.cast . Anyway, there it is, for reference ...

P.S. This solution works even with classes whose "name" is not known at compile time. This means that you can, for example, to(Class.forName("Foo")) and get a reference of type Foo . The problem is that - if your code already knew it was going to be a Foo , just make a cast to Foo ... If you did not know, this type "correct" will end up going into a more general type reference ...

Correction: Because of type erasure , this solution only works with classes whose type is known at compile time, and whose generic parameter be correct, ie:

Class<?> classe = Class.forName("String");
String st = to(classe);'

does not work.

    
04.04.2015 / 10:36
3

You have to call:

String st = to("");
Integer it = to(0);

And fix the method too:

public <E> E to(E e) {
    return (E)e;
}

See running on ideone .

    
04.04.2015 / 01:54