简体   繁体   English

用Java检查类的天气对象是否分配了类实例的方法是什么?

[英]What is way to check weather object of class is assigned an instance of class or not in Java?

I've put just small snippet of large code to explain my question: 我只用了一小段大代码来解释我的问题:

class A 
{
    B b= new B();
    B z; 
    void xyz(){
        if(// condition to check z is not assigned instance of class B){
        z=b;
        }
        else{
        z= new B();
        }
    }
}

class B{
//variables and methods
}

I want an Expression in if block of xyz() to check weather object z have assigned an instance of B or not where I've made comment in if block's bracket. 我想要一个表达式,如果xyz()的块检查天气对象z是否分配了B的实例,或者我在if的括号中进行注释的地方。 or in other way. 或其他方式。

what is a way to check weather any java object have instance of their class or not? 如何检查天气,任何java对象是否具有其类的实例?

Using instanceof you can check this 使用instanceof可以检查一下

Try this: 尝试这个:

        B b= new B();
        B z = null; 
        if( z instanceof B){
           z=b;
           System.out.println("yes");
        } else{
           z = new B();
           System.out.println("no");
        }

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

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