现在我有一个类,不得不使用泛型,定义如下1  public final class DataService<E> implements ServiceBase<E>
2  {
3      private DataService(){}
4  
5  
6      private static Object instance;
7     
8      public static <T> ServiceBase<T> getService()
9      {
10         // singleton implementation ...
11         if (instance == null)
12           instance = new DataService<T>();
13         .....
14         return (ServiceBase<T>) instance;
15     }
16 }
现在这样的逻辑,在 14 行有警告,但是我实在没有办法才采用这样的方式来实现泛型,原因是,如果 6 行的 instance 如果定义为6      private static ServiceBase<E> instance;那么立刻就会有编译错误,因为静态是不允许处理这样的泛型类型定义的。
有没有很好的解决方案,能帮助我实现下面的目标逻辑呢?6      private static ServiceBase<E> instance;14         return instance;

解决方案 »

  1.   

    interface ServiceBase<E> {}
    public final class DataService<E> implements ServiceBase<E> {    private static ServiceBase<E> instance;    public static ServiceBase<E> getService() {
            if (instance == null)
                instance = new DataService<E>();
            return instance;
        }
    }以上代码编译无误,不知道是否是你要的?
      

  2.   

    楼上的强人,我的最早想当然版本就是这样写的啊,编译报错,我贴给你看can not make a static reference to a non-static type E
    所以斗胆问问,用的 JDK 什么版本?用的什么 IDE ?我的是 JDK 1.5.11,Eclipse 3.2.1
      

  3.   

    呵呵,对不起,的确是错的。分析这个方法:public static ServiceBase<E> getService()
    在没有实例化的时候,就返回类型为E的ServiceBase实例,而且有没有任何参数指示E应该哪种类型。所以,你的目标应该是无法实现的。
      

  4.   

    仔细看了关于泛型的应用指导,我的第一目标确实无法实现,只能使用 Class<T> 来作弊了哎,这贴结了。