有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java中的模板类

假设有这样一个名为Test的类

public class Test<A extends X, B extends Y> {
    public int testing(long n) {
       a(new Good(n));
       return 1;
   }
}

我想把这个类用作Test<Good, Bad>Good类是由long类型构造的,但这不起作用,因为测试中的函数需要类型,而不是Good。在这种情况下,如何使用A类型


共 (2) 个答案

  1. # 1 楼答案

    回答不确定目的或问题是什么;但是试着理解你的目标。 看起来你想要的是一个简单的enum,不确定你是否需要包装它

    enum TestTypes {
       GOOD, BAD;
    }
    
    public class Test {
        private TestTypes result;
    
        public Test(TestTypes aResult) {
           this.result = aResult;
        }
    
    //    APART   -
    
    public int testing(long l) {
       Test t = new Test(TestTypes.GOOD);
       // do smth with t
        return 1;
    }
    
  2. # 2 楼答案

    如果我理解正确,您希望在模板类中实例化A类型的对象。模板化类仅在运行时可见,因此必须使用反射。举个简单的例子-

    public class LongConstructInitializer<T>{
    
      public void initT(T t){
        try{
            Constructor<?> constructor = t.getClass().getConstructor(Long.class);
            T anotherT = constructor.newInstance(4L);
        } //Giant catch block goes here.
      }
    

    但你想这么做的事实让我觉得你误用了泛型。你可能想重新考虑一下课堂的设计