有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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;
    }
}

现在,有一个“中产”阶级,我想注意一下,这种类型的实体已经被创造出来了。不同的类可以创建不同类型的实体

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()以查看已创建的实体的类型

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的情况下,在main中获得AEntity的类型?有没有办法做到这一点,或者有其他方法?先谢谢你

背景:

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


共 (2) 个答案

  1. # 1 楼答案

    您可以提供一个getter:

    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,您可能需要在其中进行一些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;
    }
    
  2. # 2 楼答案

    你试过一个简单的getClass电话吗

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