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?
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);
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With