How to write a generic method in Java

c#, generics, java

Solution

First, your C# example is wrong; it will throw an `InvalidCastException` unless `typeof(T) == typeof(object)`. You can fix it by adding a constraint:

public static T Resolve<T>() where T : new() {
    return new T();
}

Now, this would be the equivalent syntax in Java (or, at least, as close as we can get):

public static <T> T Resolve() {
    return (T) new T();
}

Notice the double mention of `T` in the declaration: one is the `T` in `<T>` which parameterizes the method, and the second is the return type `T`.

Unfortunately, the above does not work in Java. Because of the way that Java generics are implemented runtime type information about `T` is not available and so the above gives a compile-time error. Now, you can work around this constraint like so:

public static <T> T Resolve(Class<T> c) {
    return c.newInstance();
}

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.

Problem

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?

Original source