Created
November 2, 2019 09:59
-
-
Save AppLoidx/768e325e6e96a89f7f9606b0b6f0d200 to your computer and use it in GitHub Desktop.
Creating an instacne from class mark
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
package generics.with; | |
import java.lang.reflect.InvocationTargetException; | |
/** | |
* @author Arthur Kupriyanov | |
*/ | |
public class ClassMarkWithGenerics { | |
private <T> T getFoo(Class<T> tClass) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { | |
return tClass.getConstructor(String.class).newInstance("something init arg"); | |
} | |
public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { | |
ClassMarkWithGenerics classMarkWithGenerics = new ClassMarkWithGenerics(); | |
String s = classMarkWithGenerics.getFoo(String.class); | |
System.out.println(s); // output something init arg | |
// With custom class | |
MyClass myClass = classMarkWithGenerics.getFoo(MyClass.class); | |
myClass.printField(); // Field value : something init arg | |
} | |
} | |
class MyClass { | |
private String field; | |
public MyClass(String arg){ | |
this.field = arg; | |
} | |
void printField(){ | |
System.out.println("Field value : " + field); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment