Skip to content

Instantly share code, notes, and snippets.

@jongyeol
Created September 23, 2015 03:17
Show Gist options
  • Save jongyeol/a7e13ca6a7e3365f5a8b to your computer and use it in GitHub Desktop.
Save jongyeol/a7e13ca6a7e3365f5a8b to your computer and use it in GitHub Desktop.
generic is just casting.
import java.lang.reflect.Type;
import com.fasterxml.jackson.core.type.TypeReference;
public class JavaReturnTypeInfer{
private static String speficicType() throws Exception{
TypeReference<String> tr = new TypeReference<String>(){};
Type type = tr.getType();
System.out.println(type.getTypeName()); // => java.lang.String
return (String) Class.forName(type.getTypeName()).newInstance();
}
@SuppressWarnings("unchecked")
private static <T> T inferReturnType() throws Exception{
TypeReference<T> tr = new TypeReference<T>(){};
Type type = tr.getType();
System.out.println(type.getTypeName()); // => T
return (T) Class.forName(type.getTypeName()).newInstance(); // java.lang.ClassNotFoundException: T
}
public static void main(String[] args) throws Exception{
speficicType();
String s = inferReturnType();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment