使用Java中的泛型传递类型参数

时间:2015-07-07 17:10:08

标签: java generics

我想更多地了解泛型,我有以下情况:

// This is one of many Models I have that want to use like this, or similar
public class MyData{
    private String name;
    private String color;
    //... default constructor    

    //... setters and getters

}

我有一个抽象类:

public abstract class CacheAble<T>{

   // The idea is any T can be inserted
   public abstract <T> boolean insertCacheAble(T data);

   // The idea is any T can be deleted
   public abstract <T> boolean deleteCacheAble(T data);      

}

所以我想做的是:

 // Have my Operations for how i want to handle the methods on MyData
 public MyDataOps extends CacheAble<MyData>{

   //... Members

   public MyDataOps(){
       //.. initialize some other members
   }      

   @Override
   public <T> boolean insertCacheAble(T data){
       //... want to be able to Access MyData.name & MyData.color
       //... how can I do this?

      String name = data.getName();
      String color = data.getColor();

      //.. insert db values
   }

   @Override
   public <T> boolean deleteCacheAble(T data){

      String name = data.getName();
      String color = data.getColor();

      //... Perform db delete based on name or color
   }

 }

我不太了解Java Generics,因为你可以看到任何指向正确的方向都会非常有帮助!我应该将其实现为通用接口吗?

4 个答案:

答案 0 :(得分:2)

在您的代码中

public abstract class CacheAble<T>{
   public abstract <T> boolean insertCacheAble(T data);
   public abstract <T> boolean deleteCacheAble(T data);      
}

方法的类型参数T 与类类型参数相同T。这可能不是你想要的。首先,它使方法比你想要的更通用(你想要修复它们的签名,如果你修复了类的类型参数)。其次,这会强制您在子类中实现这些方法时使用类型参数,即使它们应该在特定类型上工作。所以这样定义:

public abstract class CacheAble<T>{
   public abstract boolean insertCacheAble(T data);
   public abstract boolean deleteCacheAble(T data);
}

此外,正如“sodik”指出的那样,您的子类特定于某种类型的T,因此不应再引用T,而只能引用特定类型{{ 1}}。然后你可以使用MyData的公共方法(比如getter和setter的颜色和名称):

MyData

答案 1 :(得分:1)

String name = data.getName();
String color = data.getColor();

您无法直接访问这些字段,因为它们是私有字段。

答案 2 :(得分:0)

@Override
   public <MyData> boolean insertCacheAble(MyData data){
       //... want to be able to Access MyData.name & MyData.color
       //... how can I do this?

      String name = data.name; // This doesn't work
      String color = data.color; // This doesn't work

      //.. insert db values
   }

T不是您使用名称或颜色的私有成员实现的类。 MyData有效。将T对象参数替换为MyData对象,一切正常。

答案 3 :(得分:0)

public class MyData{
    public Hashmap<String,Object> dataField;
    //... default constructor    

    //... setters and getters

}

...

@Override
   public boolean insertCacheAble(MyData data){


      String name = data.dataField.get("name"); 
      String color = data.dataField.get("color");

      //.. insert db values
   }

   let anObject be a <T> with field MyData myData
   insertCacheAble(anObject.myData);