使用与整数相同的构造函数获取所有对象?

时间:2018-06-16 10:49:32

标签: java constructor

我得到了以下课程:

public class Possibility {


    private String name;

    public Possibility(String name) {
        this.name = name;

    }

    public String getName() {
        return name;
    }

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

如果我现在有很多可以延伸的课程" Possibility",我怎样才能找到扩展可能性的类有多少个实例?

3 个答案:

答案 0 :(得分:1)

您可以在Possibility类中使用静态字段作为计数器,并在创建对象时使用它来递增。这比使用反射更有效,更安全。

package so;

public class Possibility {
    private static int counter = 0;

    private String name;

    public Possibility(String name) {
        counter += 1;
        this.name = name;

    }

    public String getName() {
        return name;
    }

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

    public static void main(String[] args) {
        Possibility1 p1 = new Possibility1("p1");
        Possibility2 p2 = new Possibility2("p2");

        System.out.println(Possibility.counter);
    }
}

Possibility1

package so;

public class Possibility1 extends Possibility {
    public Possibility1(String name) {
        super(name);
    }
}

Possibility2:

package so;

public class Possibility2 extends Possibility {
    public Possibility2(String name) {
        super(name);
    }
}

Possibility3

package so;

public class Possibility3 extends Possibility {
    public Possibility3(String name) {
        super(name);
    }
}

答案 1 :(得分:0)

Reflections library提供了一种非常简单的方法:

int numSubTypes = reflections.getSubTypesOf(Possibility.class).size();

答案 2 :(得分:0)

你必须在Possibility类中创建一个整数属性,你可以从另一个从Possibility扩展的类中得到这个整数,如下所示:

class Possibility{
   public int someInteger;
   //getter 
   public int getSomeInteger(){
       return this.someInteger;
   }
}

class someClass extends Possibility{
   public void someMethode(){
      Possibility possibility = new Possibility("someName");
      //get someInteger 
      possibility.getSomeInteger();
   }
}