Calling constructor of a generic type

后端 未结 6 1699
借酒劲吻你
借酒劲吻你 2020-12-10 12:48

If I have an abstract class like this:

public abstract class Item
{
    private Integer value;
    public Item()
    {
        value=new Integer(0);
    }
           


        
6条回答
  •  爱一瞬间的悲伤
    2020-12-10 13:20

    There is no way to use the Java type system to enforce that a class hierarchy has a uniform signature for the constructors of its subclasses.

    Consider:

    public class ColorPencil extends Pencil
    {
        private Color color;
    
        public ColorPencil(Color color)
        {
            super();
            this.color=color;
        }   
    }
    

    This makes ColorPencil a valid T (it extends Item). However, there is no no-arg constructor for this type. Hence, T() is nonsensical.

    To do what you want, you need to use reflection. You can't benefit from compile-time error checking.

提交回复
热议问题