Can I write something like?
<T> T metod(){ T temp; cоздание и инициализация класса типа T return temp; } Parameterized methods exist in Java, but they cannot directly create an instance of the type-parameter parameter. This can be bypassed either by passing the desired class as an additional parameter (as shown by the Senior Automator, see also https://stackoverflow.com/questions/450807/how-do-i-make-the-method-return-type-generic ) or, in some cases, you can manually check the types of actual parameters and create instances of specific types. Here is a sample code, you can play with it yourself:
public class TestGenericMethod { <T> T genericMerge(T a, T b) { System.out.printf("Inside method: %s, %s (class %s)\n", a, b, a.getClass()); String s = a.toString() + b.toString(); T result = (T)s; // remains String System.out.printf("Result: %s of class %s\n", result, result.getClass()); // T t = new T(); // нельзя Object result2; if (a.getClass().getName().contains("Integer")) result2 = Integer.valueOf(s); else // В отличие от (T)result, приводит к нужному типу, но опасно result2 = a.getClass().cast(result); System.out.printf("Result2: %s of class %s\n", result2, result2.getClass()); return (T)result2; } void run() { String s1 = "Строка 1 ", s2 = "Строка 2 "; Object o = genericMerge(s1, s2); System.out.printf(" genericMethod(%s, %s) = %s (%s)\n", s1, s2, o, o.getClass()); Integer i1 = 5, i2 = 10; o = genericMerge(i1, i2); System.out.printf(" genericMethod(%s, %s) = %s (%s)\n", i1, i2, o, o.getClass()); } public static void main(String[] args) { new TestGenericMethod().run(); } } It is possible, but a little different
public class Main { public static void main(String[] args) throws InstantiationException, IllegalAccessException { MyClass3 metod = method(MyClass3.class); System.out.println(method.getAnyString()); } private static <T> T method(Class<T> typeOfT) throws IllegalAccessException, InstantiationException { PodamFactory factory = new PodamFactoryImpl(); // данная библиотека позволяет немного забыть о reflection T myPojo = factory.manufacturePojo(typeOfT); return myPojo; } public class MyClass3 { public MyClass3() { } public String getAnyString(){ return "blabla"; } } } <!-- https://mvnrepository.com/artifact/uk.co.jemos.podam/podam --> <dependency> <groupId>uk.co.jemos.podam</groupId> <artifactId>podam</artifactId> <version>7.0.4.RELEASE</version> </dependency> Result
blabla Process finished with exit code 0 Source: https://ru.stackoverflow.com/questions/607876/
All Articles
Tvalue is not available. Closest to the desired - inheritance from the parameterized class with a specific value of the type ( article on Habré ) - zRrr