繁体   English   中英

如何在抽象类中新建一个未知对象

[英]how to new an unknown object in abstract class

我想使用构建器模式来创建一个未知对象

怎么做?

我的代码是这样的:

public abstract class abstractA<T extends GameApplication<T>>{

public static class Builder<T> {

    private JPanel panel = new JPanel();
    private JFrame frame = new JFrame();

    private int height = 0, width = 0;
    private int x = 0,y = 0;
    private Color backgroundColor = Color.BLUE;

    public Builder setFrameHeightWidth(int height, int weight) {
        this.height = height;
        this.width = weight;
        return this;
    }

    public Builder setLocation(int x, int y) {
        this.x = x;
        this.y = y;
        return this;
    }

    public Builder setbackground(Color color) {
        this.backgroundColor = color;
        return this;
    }

    public T Build(){
        //error here
        return new T ;
    }

}

我想这样使用它:

class RealA extends abstractA{


public static void main(String[] argv){
    RealA a = abstractA.builder
                .setLocation(100,200)
                .setFrameHeightWidth(500,600)
                .build();
}

}

我不能创建一个泛型对象,但我需要这个。 怎么做?

你可以排序的做(像)这个,如果你让建设者知道它是建立(通过传递一个类)之类的话,然后把它创建使用反射实例(例如类newInstance方法)。

这假设所有子类都具有零参数构造函数。 (可以修改它以使用带参数的构造函数,但每个子类都需要具有相同签名的构造函数)

例如...

public class Stack {

    static abstract class Common {
        protected String name;

        public void setName(String name) {
            this.name = name;
        }

        public abstract void doSomething();
    }

    static class Solid1 extends Common {
        @Override
        public void doSomething() {
            System.out.println("Solid1's implementation: name=" + name);
        }
    }

    static class Solid2 extends Common {
        @Override
        public void doSomething() {
            System.out.println("Solid2's implementation: name=" + name);
        }
    }

    static class Builder<T extends Common> {
        private final Class<T> clazz;
        private String name;

        public Builder(Class<T> clazz) {
            this.clazz = clazz;
        }

        public Builder<T> setName(String name) {
            this.name = name;
            return this;
        }

        public T build() {
            T t;
            try {
                t = clazz.newInstance();
            } catch (Exception e) {
                throw new RuntimeException("Bad things have happened!");
            }
            t.setName(name);
            return t;
        }
    }

    public static void main(String[] args) {
        Solid1 solid1 = new Builder<>(Solid1.class).setName("[NAME]").build();
        Solid2 solid2 = new Builder<>(Solid2.class).setName("[NAME]").build();

        solid1.doSomething();
        solid2.doSomething();
    }
}

输出...

Solid1's implementation: name=[NAME]
Solid2's implementation: name=[NAME]

不确定这是多么有用......

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM