Created
June 30, 2018 19:26
-
-
Save thepulkitagarwal/b748b283ef43de60c8978e57648f9bde to your computer and use it in GitHub Desktop.
Java Generics with Lists
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.*; | |
import java.lang.reflect.*; | |
public class Class1 { | |
public int x; | |
public Class1() { | |
// Default Constructor | |
} | |
public Class1(int x) { | |
this. x = x; | |
} | |
public static void main(String args[]) { | |
check1(); | |
check2(); | |
} | |
public static void check1() { | |
try { | |
List<Class1Extension> c1l = getList(Class1Extension.class); | |
System.out.println(c1l.get(0).getClass()); | |
System.out.println(c1l.get(0).x); | |
} catch (Exception e) { | |
} | |
} | |
public static void check2() { | |
List<Class2Extension> c2elist = new ArrayList<>(); | |
c2elist.add(new Class2Extension()); | |
List<Class1Extension> c1elist = convertList(c2elist, Class1Extension.class); | |
System.out.println(c1elist.get(0).getClass()); | |
List<Class2> c2list = new ArrayList<>(); | |
c2list.add(new Class2()); | |
List<Class1> c1list = convertList(c2list, Class1.class); | |
System.out.println(c1list.get(0).getClass()); | |
} | |
public static <T extends Class1, E extends Class2> List<T> convertList(List<E> class2List, Class<T> clazz) { | |
List<T> class1List = new ArrayList<>(); | |
for (E class2 : class2List) { | |
class1List.add((T) class2.getClass1()); | |
} | |
return class1List; | |
} | |
public static <T extends Class1> List<T> getList(Class<T> clazz) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { | |
List<T> class1List = new ArrayList<>(); | |
for (int i = 0; i < 100; i += 1) { | |
class1List.add(clazz.getConstructor(int.class).newInstance(i)); | |
} | |
return class1List; | |
} | |
} | |
class Class1Extension extends Class1 { | |
public Class1Extension() { | |
} | |
public Class1Extension(int x) { | |
this.x = x + 1; | |
} | |
} | |
class Class2 { | |
public int y; | |
public Class1 getClass1() { | |
return new Class1(); | |
} | |
} | |
class Class2Extension extends Class2 { | |
public Class1Extension getClass1() { | |
return new Class1Extension(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment