简体   繁体   English

Java-如何在类定义中检查对象是否是类的实例

[英]Java - How to check if an object is an instance of a class in the class definition

Code: 码:

public class Composite extends Component implements Iterable<Component>{

    private List<Component> caseComponents = new ArrayList<Component>();


    @Override
    public Iterator<Component> iterator(){
        return new CompIterator();
    }



    private class CompIterator implements Iterator{
        int index = 0;

        @Override
        public boolean hasNext(){
            if(index<caseComponents.size()){
                return true;
            }
            return false;
        }

        @Override
        public Object next() {
            if(this.hasNext()){
                return caseComponents.get(index++);
            }
            return null;
        }
    }


    public String breadthFirst() {
        Queue<Component> q = new LinkedList<Component>();
        StringBuilder stringRep = new StringBuilder();
        q.add(this);

        while(q.element()!=null){
            Component first = q.remove();
            System.out.println(first.name);

            for(Component c : first.caseComponents){
                q.add(c);
            }
        }
    }

I'm trying to do a breadth first print of a tree of the Composite design pattern. 我正在尝试对Composite设计模式的树进行广度优先打印。 I have declared a method that is supposed to be called by the "root" of the tree. 我已经声明了应该由树的“根”调用的方法。 In the tree, there will be objects of the classes Composite and Leaf . 在树中,将存在类CompositeLeaf对象。 These both inherit from Component , but are of course different. 这些都继承自Component ,但是当然有所不同。 Composite is a container objects as well as an object itself, while Leaf is just one object. Composite是容器对象以及对象本身,而Leaf只是一个对象。 I want to change my code so that the line for(Component c : first.caseComponents) is only executed if first is an instance of Composite , otherwise it would try to iterate over a Leaf which is not possible. 我想更改代码,以便仅当firstComposite的实例时才执行for(Component c : first.caseComponents)行,否则它将尝试遍历Leaf ,这是不可能的。 How can I make it so that the for statement is only entered if first is a Composite ? 我怎样才能使for语句仅在firstComposite时才输入?

Use instanceof to check if comp is an instance of Composite . 使用instanceof检查comp是否为Composite的实例。

eg: 例如:

if (comp instanceof Composite) { 
    //do something
}

You can restructure your code to apply the visitor pattern: 您可以重组代码以应用访问者模式:

public interface ComponentVisitor {
  void visitComposite(Composite composite);
  void visitLeaf(Leaf leaf);
}

public interface Component {
  void acceptVisitor(ComponentVisitor visitor);
}

public class Composite implements Component {
  @Override public void acceptVisitor(ComponentVisitor visitor) {
    visitor.visitComposite(this);
  }
}

public class Leaf implements Component {
  @Override public void acceptVisitor(ComponentVisitor visitor) {
    visitor.visitLeaf(this);
  }
}

The visitor pattern is a compile-time safe alternative to runtime checks and casts and can also help static analysis of your code. 访问者模式是运行时检查和强制转换的一种编译时安全替代方法,它还可以帮助您对代码进行静态分析。 The program code will look like 程序代码看起来像

public class ComponentPrinter implements ComponentVisitor {

  public void printComponent(Component component) {
    component.acceptVisitor(this);
  }

  @Override public void visitComposite(Composite composite) {
    for (Component child : composite) {
      printComponent(component);
    }
  }

  @Override public void visitLeaf(Leaf leaf) {
    System.out.println("Found leaf: " + leaf);
  }
}

Incidentally, the demo program does a depth-first print, but you can of course use a queue to accumulate components and then print breadth-first 顺便说一句,演示程序进行深度优先打印,但是您当然可以使用队列来累积组件,然后先进行广度优先打印

I would get rid of both Composite and Leaf altogether, and introduce a Node class that can have children. 我将完全摆脱Composite和Leaf,并介绍一个可以有孩子的Node类。 If it does, it's an intermediate node; 如果是这样,则它是一个中间节点。 if not, it's a leaf. 如果没有,那是一片叶子。 As this property can change any time, it is violently inappropriate to use different classes to express it. 由于此属性可以随时更改,因此使用不同的类来表达它是非常不合适的。

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

相关问题 用Java检查类的天气对象是否分配了类实例的方法是什么? - What is way to check weather object of class is assigned an instance of class or not in Java? 如何传递类名作为参数,然后使用它来检查对象是否是Java中该类的实例? - How to pass class name as parameter and then using it to check if an object is an instance of that class in java? 如何检查一个类的特定实例是否在java中运行? - how to check if a specific instance of a class is running in java? 如何检查一个类在Java中是否有任何实例? - How to check if a class has any instance in Java? object是类的实例(java) - object is an instance of class (java) 没有类定义的反序列化对象实例 - Deserialized object instance without class definition Java:如何检查对象是否是非静态内部类的实例,而不管外部对象是什么? - Java: How to check if an object is an instance of a non-static inner class, regardless of the outer object? Java:如何创建具有“Class”对象的实例? - Java: how create instance having the "Class" object? Java:如何确定对象是父类或子类的实例 - Java: How to if a object is instance of parent class or subclass 如何在Clojure中将Java类实例转换为Object [] - How to cast a Java class instance to Object[] in Clojure
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM