Java如何知道对象的类型已经创建

时间:2014-10-27 13:40:10

标签: java inheritance

我有两个继承自另一个类的类

class AEntity {
    private String name;
    public AEntity(String name){this.name = name;}
}

class Course extends AEntity {
    private String code;
    public Course(String name, String code){
        super(name);
        this.code = code;
    }
}

class Classroom extends AEntity {
    private String code;
    public Classroom(String name, String code){
        super(name);
        this.code = code;
    }
}

现在,有一个"中间"我想要注意AEntity类型的类已被创建。不同的类可以创建不同类型的AEntity。

class AEntityDefinition {
    private AEntity entity;
    public void setEntity(AEntity ae){this.entity = ae;}
    public AEntity getEntity(){return this.entity;}
}

现在,我有一个创建AEntity类实例的类,因此我使用AEntityDefinition类。

class C1 {
    private AEntityDefinition aEntityDefinition;
    public C1(){
        aEntityDefinition = new AEntityDefinition();
        aEntityDefinition.setEntity(new Course("Course","Course code"));
    }
}

最后,我想调用getEntity()以查看已创建的AEntity的类型。

public class EntityDefinition {
    public static void main(String[] dgf){
        AEntityDefinition aEntityDefinition = new AEntityDefinition();
        System.out.println(aEntityDefinition.getEntity() instanceof Course);
        System.out.println(aEntityDefinition.getEntity());
    }
}

运行项目会返回null,因为在类外部不知道entity变量。我的问题是:如果不从C1传递,我将如何获得主要内部的AE类型?有没有办法做到这一点,还是有另一种方法?提前谢谢。

上下文:

我有一些客户端代码在AEntityDefinition中创建并存储AEntity,AEntityDefinition是另一个(未指定的)类中的字段。我希望能够在不更改客户端类的代码的情况下解决这个问题,或者最好不要这样做,因为有许多类可能是容器。

2 个答案:

答案 0 :(得分:1)

你可以提供一个吸气剂:

class C1 {
    private AEntityDefinition aEntityDefinition;
    public C1(){
        aEntityDefinition = new AEntityDefinition();
        aEntityDefinition.setEntity(new Course("Course","Course code"));
    }

    public Class<? extends AEntity> getEntityType() {
        return aEntityDefinition.getEntity().getClass();
    }
}

如果实体定义或实体可以为null,您可能希望在那里进行一些空检查。


如果您无法更改C1类,但是您知道它有AEntityDefinition字段,并且您希望获得对其中的AEntity实例的引用,请使用反射:

public static Class<? extends AEntity> getEntityType(Object o) throws Exception {
    for (Field field : o.getClass().getDeclaredFields()) {
        if (AEntityDefinition.class.isAssignableFrom(field.getType())) {
            AEntityDefinition def = (AEntityDefinition) field.get(o);
            return def.getEntity().getClass();
        }
    }
    return null;
}

答案 1 :(得分:1)

您是否尝试过简单的getClass电话?

AEntity ae = aEntityDefinition.getEntity();
String klass = ae != null ? ae.getClass().getName() : "*not defined*";
System.out.println("The class type is " + klass);