Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Generic instance of type in Java [duplicate]

I have the following Java class

public class MyClass <T extends MyInterface> implements RowMapper<MyInterface>

I'm implementing the following method:

@Override
public T mapRow(ResultSet rs, int arg1) throws SQLException {

How can I create an instance of 'T' type on that class?

I tried to define the T type class and use "myInstance.newInstance()" but I was unable to define it. Sending the Class as a parameter to the method and using the "newInstance()" method works, but I want to be able to do so without having to pass it as a param. Thanks!

like image 235
Omri Avatar asked Aug 29 '12 11:08

Omri


1 Answers

Java generics are implemented by erasure which means there will be no parameter type information at runtime. You won't know the T class at runtime (there is not such T.class). So you need to pass the Class object as a method parameter in order to do what you want.

like image 131
dcernahoschi Avatar answered Sep 23 '22 02:09

dcernahoschi