Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a generic method in Java?

Tags:

java

generics

I have the following method:

public static void update(String name) {
    CustomTextType obj = findByName(name);
    ...
}

I'd like to make it a general use method so that I don't need to write new code for every new custom type. I could do this, which would require instantiating the object before calling update():

public static void update(String name, Object obj) {
    obj = findByName(name);
    ...
}

Out of curiosity, I'm wondering if there is a way to do this using Java Generics:

// note: this is an example and does not work
public static void update(String name, <T> type) {
    type var = findByName(name);
    ...
}

Is there a way to accomplish this in Java?

like image 779
TERACytE Avatar asked Sep 18 '13 19:09

TERACytE


People also ask

How do you declare a generic method in Java?

For static generic methods, the type parameter section must appear before the method's return type. The complete syntax for invoking this method would be: Pair<Integer, String> p1 = new Pair<>(1, "apple"); Pair<Integer, String> p2 = new Pair<>(2, "pear"); boolean same = Util. <Integer, String>compare(p1, p2);

How do you write a generic method?

All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example). Each type parameter section contains one or more type parameters separated by commas.

What is generics in Java with example?

Generics add that type of safety feature. We will discuss that type of safety feature in later examples. Generics in Java are similar to templates in C++. For example, classes like HashSet, ArrayList, HashMap, etc., use generics very well.


1 Answers

public static <T> void update(String name, T type) {
    //logic dealing with `T`.
}

Note that T will be reifiable in this case. Either Foo<T>(which itself includes Class<T> that can be obtained from instanceOfT.getClass()) or T itself has been passed in.

like image 97
nanofarad Avatar answered Sep 19 '22 18:09

nanofarad