How to write a generic method in Java.
In C# I would do this
public static T Resolve<T>()
{
return (T) new object();
}
Whats the equivalent in Java?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
First, your C# example is wrong; it will throw an
InvalidCastExceptionunlesstypeof(T) == typeof(object). You can fix it by adding a constraint:Now, this would be the equivalent syntax in Java (or, at least, as close as we can get):
Notice the double mention of
Tin the declaration: one is theTin<T>which parameterizes the method, and the second is the return typeT.Unfortunately, the above does not work in Java. Because of the way that Java generics are implemented runtime type information about
Tis not available and so the above gives a compile-time error. Now, you can work around this constraint like so:Note the need to pass in
T.class. This is known as a runtime type token. It is the idiomatic way of handling this situation.