gpt4 book ai didi

Java 泛型到变量

转载 作者:行者123 更新时间:2023-12-01 07:18:45 25 4
gpt4 key购买 nike

java泛型如何分配给变量然后传递它? 我不想这样做:

MyClass myClass = new MyClass();

if (someCondition) {
myClass.<Foo>getDetails();
} else if (someCondition) {
myClass.<Bar>getDetails();
} ... more conditional objects

我怎样才能做到这一点:

MyClass myClass = new MyClass();
JavaGeneric jg;
if (someCondition) {
jg = Foo;
} else if (someCondition) {
jg = Bar;
}

myClass.<jg>getDetails();

这可能吗?我尝试搜索有关 java generics 的文档但没有这样的示例或如何将其分配给变量,他们只有将其传递到 method/class (T) 的示例.

更新:

getDetails()位于 object :

public class MyClass {
<T> void getDetails() {
//call method that uses T...
}
}

最佳答案

interface JavaGeneric {
public String getDetails(); //also you can have default methods implementation here.
}

class Foo implements JavaGeneric {
public String getDetails(){
return "Foo Details";
}
}


class Bar implements JavaGeneric {
public String getDetails(){
return "Bar Details";
}
}


// Somewhere in code

JavaGeneric jg;
if (someCondition) { //lets say this is false
jg = Foo;
} else if (someCondition) { // lets say this is true
jg = Bar;
}

jg.getDetails(); //we will get "Bar Details"

关于Java 泛型到变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48418546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com