1

我有一个任务要求我使用工厂模式来实现不可变的数据结构,但问题是抽象类是泛型的,并且让静态方法引用泛型类型给我带来了问题。我的任务是要求我使用静态方法,所以我开始恐慌。有什么帮助/建议吗? 编辑添加了一些示例代码,这里是教授给我们签名的一种方法的规范:

ExampleClass.method1 : ExampleClass, T -> ExampleClass

ExampleClass.method2 : ExampleClass -> T

public abstract class ExampleClass<T>{

   //static method creates a new subclass of Example ("Push" method)
   public static Class method1(T x, ExampleClass c){
       return new method1(x, f);
    }   

   //Supposed to return an object type T ("pop" method)
   public static T method2(ExampleClass c){
       return c.method2Dynamic();
   }

我喜欢的这两种方法都给我带来了日食问题。

4

3 回答 3

3

我不知道你真正想要做什么,但让我们假设问题是你只是在寻找正确的语法:

public class ExampleClass<T> {
    public static <T> Class<T> method1(T x, ExampleClass<T> c) {
        return c.method3(x);
    }
    public static <T> T method2(ExampleClass<T> c) {
        return c.method2Dynamic();
    }
    private Class<T> method3(T x) {
        return null;
    }
    private T method2Dynamic() {
        return null;
    }
}
于 2010-09-23T04:19:34.660 回答
0

有关泛型方法(相对于泛型类)的帮助, 请参阅Java 教程。

从您到目前为止的描述来看,静态方法与实例方法的问题不应该在这里发挥作用。

于 2010-09-23T04:00:10.060 回答
0

If you have a generified class, you can't use the type parameters in static methods since they don't make sense there. For example, consider ArrayList<T>. You can create a ArrayList<String> stingList = new ArrayList<String>() and a ArrayList<Integer> integerList = new ArrayList<Integer>. So now you have to instances of ArrayList, each with their own parameter type, and instance methods that can take advantage of that parameter type like get. But static methods belong to the class not the instance, so when you call a static method you call it like ArrayList.staticMethod() NOT stringList.staticMethod() or integerList.staticMethod() (you can do that as well, but it doesn't really make sense, since the static method cannot access instance variables, so it does the exact same thing as calling it on the class). But when you call it on the class, the class is just ArrayList, without any type parameters, since the type parameters are only used by instances.

You can however have methods that have their own type parameter, which is independent of the type parameter of the class, like Thomas shows in his answer. So you can then call those method like ExampleClass.<String> staticMethod(); notice that ExampleClass has no type parameter here, but the method does have it. (you can omit the <String> in the method call if the compiler can infer it from the parameters used, or the return type: String s = ExampleClass.method2(new ExampleSubclass<String>()); it usually does a pretty good job at inferring it)

于 2010-09-23T08:51:45.637 回答