How to write a generic method in Java

How to write a generic method in Java.

In C #, I would do it

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

What is the equivalent in Java?

+3
source share
4 answers

Firstly, your C # example is incorrect; he will throw InvalidCastException, if only typeof(T) == typeof(object). You can fix this by adding a restriction :

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

Now this will be the equivalent Java syntax (or at least as close as possible):

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

Note the double mention Tin the declaration: one is Tin <T>, which parameterizes the method, and the second is the return type T.

, Java. - , Java , T , . :

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

T.class. . .

+11

, Java - :

@SuppressWarnings("unchecked")
public static <T> T resolve() {
  return (T) new Object();
}

@SuppressWarnings, , Java, . : :

String s = <String>resolve();

.

, , , new T() #. Java. - Class<T> , . , :

public static <T> T resolve(Class<T> type) {
  try {
    return type.newInstance();
  } catch(Exception e) {
    // deal with the exceptions that can happen if 
    // the type doesn't have a public default constructor
    // (something you could write as where T : new() in C#)
  }
}

, , :

public static <T> T resolve(Class<T> type) {
  return type.cast(new Object());
}

, , - , , T - , Object.

+2

http://java.sun.com/docs/books/tutorial/extra/generics/methods.html

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

(T), , . , . ...

+1

- factory:

 public interface MyFactory<T> {
     T newInstance();
 }

, . :

public static T resolve<T>(MyFactory<T> factory) {
    return factory.newInstance();
}

: !

0

Source: https://habr.com/ru/post/1727941/


All Articles