Created
February 20, 2020 15:34
-
-
Save gelin/062a447064110f7c563595cc7f9f9109 to your computer and use it in GitHub Desktop.
Small test for generic method to return parametrized type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
import java.util.Map; | |
// http://stackoverflow.com/questions/3437897/how-to-get-a-class-instance-of-generics-type-t | |
public class GenericsTest { | |
public static class MyClass extends Object { | |
} | |
private static <T> T create(Class<T> clazz) throws IllegalAccessException, InstantiationException { | |
return clazz.newInstance(); | |
} | |
private static void testCreationByClass() throws InstantiationException, IllegalAccessException { | |
MyClass object = create(MyClass.class); | |
System.out.println(object); // output: GenericsTest$MyClass@3764951d | |
Integer integer = create(MyClass.class); // compilation error: incompatible types: GenericsTest.MyClass cannot be converted to java.lang.Integer | |
} | |
private static <T> T create(String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException { | |
Class clazz = Class.forName(className); | |
Object instance = clazz.newInstance(); | |
return (T) instance; | |
} | |
private static void testCreationByClassName() throws IllegalAccessException, InstantiationException, ClassNotFoundException { | |
MyClass object = create(MyClass.class.getName()); | |
System.out.println(object); // output: GenericsTest$MyClass@4b1210ee | |
Integer integer = create(MyClass.class.getName()); // runtime exception: java.lang.ClassCastException: GenericsTest$MyClass cannot be cast to java.lang.Integer | |
} | |
private static Map<String, Object> instances = new HashMap<String, Object>(); | |
static { | |
instances.put("myClass", new MyClass()); | |
instances.put("string", "I'm string"); | |
} | |
private static <T> T get(String key) { | |
return (T) instances.get(key); | |
} | |
private static void testGenericGetter() { | |
MyClass object = get("myClass"); | |
System.out.println(object); // output: GenericsTest$MyClass@4b1210ee | |
String string = get("string"); | |
System.out.println(string); // output: I'm string | |
Integer integer = get("myClass"); // runtime exception: java.lang.ClassCastException: GenericsTest$MyClass cannot be cast to java.lang.Integer | |
} | |
public static void main(String[] args) throws Exception { | |
testCreationByClass(); | |
testCreationByClassName(); | |
testGenericGetter(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment