簡體   English   中英

Java泛型到變量

[英]Java Generics to variable

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();
}

並且,現在在類中實現它。

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

和,

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

現在,在if-else創建實例,並在最后調用getDetails方法

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

jg.getDetails ();

==更新==

我不太確定,您到底想達到什么目標。 但是,假設您需要概括化getDetails方法的返回類型。

interface JavaGeneric<T>
{
   public T getDetails();
}

然后,在實施時

class Foo<T> implements JavaGeneric<T>
{
     public T getDetails()
     {
          // your code
     }
}
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"

剛打電話

myClass.getDetails()

由於類型擦除,兩者之間沒有區別

myClass.<T>getDetails()

myClass.<R>getDetails()

似乎僅是因為要在方法主體中使用類型變量T才將getDetails()聲明為泛型。 類型變量T不是方法簽名或其返回類型的一部分。

通常不需要。 根據您的方法實際執行的操作,也許您可​​以從方法聲明中刪除<T>並將T替換為? 郵件正文中的任何地方。

如果要將類型從變量傳遞給方法,請使用Class<?>參數:

public class MyClass {
   void getDetails(Class<?> cls) {
      //...
   }
}

然后,您只需要一個Class<?>類型的對象:

MyClass myClass = new MyClass();
Class<?> jg;
if (someCondition) {
   jg = Foo.class;
} else if (someCondition) {
   jg = Bar.class;
}

myClass.getDetails(jg);

由於類型擦除 ,泛型僅在編譯時存在,因此無法從運行時變量傳遞泛型類型參數。 目前尚不清楚您對getDetails的類型實際上在做什么,但是如果您不能使其與Class<?>對象一起使用,則需要堅持第一個示例中的代碼並使用單獨的方法調用每種顯式類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM