- Create instance of generic type in Java?
- Type Inference for Generic Instance Creation
- Type Inference and Generic Constructors of Generic and Non-Generic Classes
- Java, как в generic-методе создать экземпляр generic-класса?
- how can we Create instance for generic type in java
- Join the world’s most active Tech Community!
- Welcome back to the World’s most active Tech Community!
- Subscribe to our Newsletter, and get personalized recommendations.
- TRENDING CERTIFICATION COURSES
- TRENDING MASTERS COURSES
- COMPANY
- WORK WITH US
- DOWNLOAD APP
- CATEGORIES
- CATEGORIES
Create instance of generic type in Java?
To create an instance of a generic type in Java, you can use the newInstance() method of the Class class, along with the Type and TypeVariable classes.
Here is an example of how you can create an instance of a generic type:
import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; public class MyClass < private final Class type; public MyClass() < Type t = getClass().getGenericSuperclass(); ParameterizedType pt = (ParameterizedType) t; type = (Class) pt.getActualTypeArguments()[0]; > public T createInstance() throws InstantiationException, IllegalAccessException < return type.newInstance(); > >
In this example, the MyClass class has a generic type parameter T , and the createInstance() method creates an instance of T using the newInstance() method of the Class class.
To use the MyClass class, you can create a subclass that specifies a concrete type for T , like this:
public class MySubClass extends MyClass < >MySubClass subClass = new MySubClass(); String s = subClass.createInstance(); // s is a new instance of String
Keep in mind that the newInstance() method requires a default constructor, so the class that you are trying to instantiate must have a public or default (package-private) no-arg constructor. If the class does not have a suitable constructor, you will get a java.lang.InstantiationException at runtime.
Type Inference for Generic Instance Creation
You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters ( <> ) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond.
For example, consider the following variable declaration:
In Java SE 7, you can substitute the parameterized type of the constructor with an empty set of type parameters ( <> ):
Note that to take advantage of automatic type inference during generic class instantiation, you must specify the diamond. In the following example, the compiler generates an unchecked conversion warning because the HashMap() constructor refers to the HashMap raw type, not the Map> type:
Map> myMap = new HashMap(); // unchecked conversion warning
Java SE 7 supports limited type inference for generic instance creation; you can only use type inference if the parameterized type of the constructor is obvious from the context. For example, the following example does not compile:
List list = new ArrayList<>(); list.add("A"); // The following statement should fail since addAll expects // Collection extends String>list.addAll(new ArrayList<>());
Note that the diamond often works in method calls; however, it is suggested that you use the diamond primarily for variable declarations.
In comparison, the following example compiles:
// The following statements compile: List extends String>list2 = new ArrayList<>(); list.addAll(list2);
Type Inference and Generic Constructors of Generic and Non-Generic Classes
Note that constructors can be generic (in other words, declare their own formal type parameters) in both generic and non-generic classes. Consider the following example:
class MyClass < MyClass(T t) < // . >>
Consider the following instantiation of the class MyClass , which is valid in Java SE 7 and prior releases:
This statement creates an instance of the parameterized type MyClass ; the statement explicitly specifies the type Integer for the formal type parameter, X , of the generic class MyClass . Note that the constructor for this generic class contains a formal type parameter, T . The compiler infers the type String for the formal type parameter, T , of the constructor of this generic class (because the actual parameter of this constructor is a String object).
Compilers from releases prior to Java SE 7 are able to infer the actual type parameters of generic constructors, similar to generic methods. However, the compiler in Java SE 7 can infer the actual type parameters of the generic class being instantiated if you use the diamond ( <> ). Consider the following example which is valid for Java SE 7 and later:
MyClass myObject = new MyClass<>("");
In this example, the compiler infers the type Integer for the formal type parameter, X , of the generic class MyClass . It infers the type String for the formal type parameter, T , of the constructor of this generic class.
Java, как в generic-методе создать экземпляр generic-класса?
Есть другой класс, который должен в одном из методов создать экземпляр класса Foo. Хочется при обращении к этому методу передать тип для создаваемого экземпляра класса Foo. Предположительно (код неверный) это должно быть что-то вроде:
class Abs < public Foo createFoo() < return new Foo(); > > . Abs abs = new Abs(); Foo foo = abs.createFoo();
знаю, что в шарпе есть методы, принимающие тип данных в скобках <>. А в яве как быть?
На выбор: 1)выброси яву, она несовременное умирающее говно.
2) Так никто не пишет, генерики не нужны, стирай типы, делай фабрики.
Если хочешь создавать объекты, передавай Class
Ты компилятору не пробовал скормить то что написал в вопросе?
Ты дал неправильные советы по всем пунктам, кроме последнего: тебя действительно стоит забанить.
Ты дал неправильные советы по всем пунктам, кроме последнего: тебя действительно стоит забанить.
Никак. Невозможно это. В runtime нет информации о типе. Увы, так криво реализовано это в JVM (потому что появилось не сразу, а добавили потом, не нарушая обратной совместимости).
2. В С# это не помешало впилить генерики.
2) ну допустим, фабрики, ок. погуглил немного. остался вопрос: как вызвать newInstance() с параметром (конструктор же — у меня класс Foo в конструкторе имеет параметр) у генерик типа? получилось состряпать это, но оно не компилируется:
class Api < public Foo makeRequest(Class c) < return Foo.class.getDeclaredConstructor(Api.class).newInstance(this); > >
3) вот что за мода пошла на этот «я поищу за тебя». знал бы я, что именно искать — не спрашивал здесь бы.
зы. а ты кто именно из забанов: герцог или рыба?
how can we Create instance for generic type in java
- All categories
ChatGPT (11)
Apache Kafka (84)
Apache Spark (596)
Azure (145)
Big Data Hadoop (1,907)
Blockchain (1,673)
C# (141)
C++ (271)
Career Counselling (1,060)
Cloud Computing (3,469)
Cyber Security & Ethical Hacking (162)
Data Analytics (1,266)
Database (855)
Data Science (76)
DevOps & Agile (3,608)
Digital Marketing (111)
Events & Trending Topics (28)
IoT (Internet of Things) (387)
Java (1,247)
Kotlin (8)
Linux Administration (389)
Machine Learning (337)
MicroStrategy (6)
PMP (423)
Power BI (516)
Python (3,193)
RPA (650)
SalesForce (92)
Selenium (1,569)
Software Testing (56)
Tableau (608)
Talend (73)
TypeSript (124)
Web Development (3,002)
Ask us Anything! (66)
Others (2,231)
Mobile Development (395)
UI UX Design (24)
Join the world’s most active Tech Community!
Welcome back to the World’s most active Tech Community!
Subscribe to our Newsletter, and get personalized recommendations.
Sign up with Google
Signup with Facebook
Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP
TRENDING CERTIFICATION COURSES
- DevOps Certification Training
- AWS Architect Certification Training
- Big Data Hadoop Certification Training
- Tableau Training & Certification
- Python Certification Training for Data Science
- Selenium Certification Training
- PMP® Certification Exam Training
- Robotic Process Automation Training using UiPath
- Apache Spark and Scala Certification Training
- Microsoft Power BI Training
- Online Java Course and Training
- Python Certification Course
TRENDING MASTERS COURSES
- Data Scientist Masters Program
- DevOps Engineer Masters Program
- Cloud Architect Masters Program
- Big Data Architect Masters Program
- Machine Learning Engineer Masters Program
- Full Stack Web Developer Masters Program
- Business Intelligence Masters Program
- Data Analyst Masters Program
- Test Automation Engineer Masters Program
- Post-Graduate Program in Artificial Intelligence & Machine Learning
- Post-Graduate Program in Big Data Engineering
COMPANY
WORK WITH US
DOWNLOAD APP
CATEGORIES
CATEGORIES
- Cloud Computing
- DevOps
- Big Data
- Data Science
- BI and Visualization
- Programming & Frameworks
- Software Testing © 2023 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved. Terms & ConditionsLegal & Privacy