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, type) {
type var = findByName(name);
...
}
Is there a way to accomplish this in Java?
解决方案
public static void update(String name, T type) {
//logic dealing with `T`.
}
Note that T will be reifiable in this case. Either Foo(which itself includes Class that can be obtained from instanceOfT.getClass()) or T itself has been passed in.