通用类中通用类型的访问方法 [英] Access methods of generic type in generic class

查看:67
本文介绍了通用类中通用类型的访问方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我构造了一个以String类型作为参数的泛型类.在类内部,我想访问String类型的方法.但是我得到了一个错误,无法解决符号-有人看到了这个问题:

In Java I construct a generic class with a String type as parameter. Inside the class, I'd like to access methods of the String type. But I am given an error cannot resolve symbol -- Anyone see the problem with this:

public final class App
  public static void main(String[] args) {
    MyClass<String> myClass = new MyClass<String>("some string");
  }
}

public class MyClass<T> {
  public MyClass(T someString) {
    String someSubString = someString.substring(2,3);
  }
}

这是一个更新:确实我使用String作为占位符-真的想做的是:

This is an update: Really I was using String as a placeholder -- Really what I'd like to do is:

public final class App
  public static void main(String[] args) {
    MyClass<SpecificType2> myClass = new MyClass<SpecificType2>();
  }
}

public class GeneralType {
    public methodOfSpecificType() {...}
}

public class SpecificType1 extends GeneralType {
    @Override
    public methodOfSpecificType() {...}
}

public class SpecificType2 extends GeneralType {
    @Override
    public methodOfSpecificType() {...}
}

public class MyClass<T> {
  public MyClass(T specificType) {
    specificType.methodOfSpecificType();
  }
}

推荐答案

编译器通过您的示例所知道的全部是 T Object . substring(int,int)不是属于 Object 类的方法,因此它不能保证 substring 存在,因此失败进行编译.

All the compiler knows by your example, is that T is an Object. substring(int,int) is not a method that belongs to the Object class so it can not guarantee that substring will exist, therefore it fails to compile.

如果您希望能够在此处访问 substring ,则泛型确实不适用于此解决方案.您应该只将 T 作为 String .仅在需要泛型功能时才使用泛型.

If you want to be able to access substring here, then generics is really not for this solution. You should just have T as a String. You only use generics when you have need for generic functionality.

额外阅读

这篇关于通用类中通用类型的访问方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆