I have a problem like below:
List<T> someList;
for(T element : someList){
System.out.println(element.getName()); //cannot resolve method 'getName'
}
how to get method from generic type?
my T
is a class where I have many parameters with setters and getters,
can someone tell me how to get
some params from T
class?
thanks for any help
T
needs to be upper-bounded to a type which has the getName()
method.
For example:
interface HasGetName {
String getName();
}
Then add your upper-bound using T extends HasGetName
:
// If T is a class-level type variable:
class YourClass<T extends HasGetName> {
List<T> someList;
void print() {
for(T element : someList){
System.out.println(element.getName());
}
}
}
// If T is a method-class-level type variable:
class YourClass {
<T extends HasGetName> void print(List<T> someList) {
for(T element : someList){
System.out.println(element.getName());
}
}
}
The safest way would be something like:
List<T> someList;
for(T element : someList){
if (element instanceof SpecializedElement)
System.out.println(((SpecializedElement)element).getName());
}
Java 15 introduces something cool List someList;
for(T element : someList){
if (element instanceof SpecializedElement s)
System.out.println(s.getName());
}
You don't need to do any casting with instanceof + class + any var name
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.