Java 如何声明字段级类型参数?

Java 如何声明字段级类型参数?,java,generics,Java,Generics,在以下代码sniplet中,我想指定: 附件和处理程序共享一个泛型类型` 仅当调用notify时才需要指定的类型 调用notify是可选的。 我不想强迫用户在类构造时指定,因为他们可能永远不会调用notify 这在Java下可能吗?如果没有,你会建议我怎么做 更新:我不需要指定与附件关联的处理程序和与notify关联的处理程序必须相同。我试图指定的只是附件和处理程序必须使用相同的类型 这在Java下可能吗 否–类必须知道A,因为它在所述类的成员中使用 如果没有,你会建议我怎么做 这里可能不需要泛

在以下代码sniplet中,我想指定:

附件和处理程序共享一个泛型类型` 仅当调用notify时才需要指定的类型 调用notify是可选的。 我不想强迫用户在类构造时指定,因为他们可能永远不会调用notify

这在Java下可能吗?如果没有,你会建议我怎么做

更新:我不需要指定与附件关联的处理程序和与notify关联的处理程序必须相同。我试图指定的只是附件和处理程序必须使用相同的类型

这在Java下可能吗

否–类必须知道A,因为它在所述类的成员中使用

如果没有,你会建议我怎么做

这里可能不需要泛型类型。使用接口或对象。如果类型安全性对接口很重要,则可以简单地使用强制转换

public class OperationBuilder 
{ 
  private Object attachment = null; 
  private Object handler = null; 

  public <A> OperationBuilder notify(A attachment, CompletionHandler<Integer, A> handler) 
  { 
    this.attachment = attachment; 
    this.handler = handler; 
    return this; 
  } 
} 
这在Java下可能吗

否–类必须知道A,因为它在所述类的成员中使用

如果没有,你会建议我怎么做

这里可能不需要泛型类型。使用接口或对象。如果类型安全性对接口很重要,则可以简单地使用强制转换

public class OperationBuilder 
{ 
  private Object attachment = null; 
  private Object handler = null; 

  public <A> OperationBuilder notify(A attachment, CompletionHandler<Integer, A> handler) 
  { 
    this.attachment = attachment; 
    this.handler = handler; 
    return this; 
  } 
} 
如果以后要使用附件/处理程序,则必须在那时将它们转换为适当的类型,这可能会导致运行时类型转换错误


如果以后要使用附件/处理程序,则必须将它们转换为适当的类型,这可能会导致运行时类型转换错误。

最接近的方法是让notify返回一个用a键入的桥对象。大致如下:

  public class OperationBuilder
  {

    public Bridge<A> OperationBuilder notify(A a, CompletionHandler<Integer, A> h)
    {
       return new Bridge<A>(a, h);
    }

    protected abstract<A> void build(Bridge<A> b);



    public class Bridge<A>
    {
        private A attachment;
        private CompletionHandler<Integer, A> handler;

        public Bridge(A a, CompletionHandler<Integer, A> h)
        {
           attachment = a;
           handler = h;
        }


        public void build()
        {
           build(this); // Will invoke OperationBuilder.build()
        }               
    }
  }

您可以做的最接近的事情是让notify返回一个用a键入的桥对象。大致如下:

  public class OperationBuilder
  {

    public Bridge<A> OperationBuilder notify(A a, CompletionHandler<Integer, A> h)
    {
       return new Bridge<A>(a, h);
    }

    protected abstract<A> void build(Bridge<A> b);



    public class Bridge<A>
    {
        private A attachment;
        private CompletionHandler<Integer, A> handler;

        public Bridge(A a, CompletionHandler<Integer, A> h)
        {
           attachment = a;
           handler = h;
        }


        public void build()
        {
           build(this); // Will invoke OperationBuilder.build()
        }               
    }
  }