简体   繁体   中英

How to determine an object's class in Java?

How to determine an object's class in Java?

Class B and class C extend class A. This is a method implementation in class D called dmethod(object of B or C) ,it except a single parameter that can be object of B or C.

The calling methods can be

  1. dmethod(B object)
  2. dmethod(C object)

How to write code for this scenario?

Inside dmethod(Object o) ,

use:

if(o instanceof B) {
     // ...
}
else if( o instanceof C) {
     // ...
}

to find out if the argument passed in is a B object or C object?

More on instanceof .

To determine an object's class, start with:

Object.getClass()

and go from there.

Once you have actual Class object for your particular object you can interrogate the API for information like its name and so on.

For part (2) of your question, if both B and C extend A, then you can define dmethod() like this:

dmethod(A a)

The method can then act on anything that is common to both B and C, ie. in their superclass (A). If you need something specific to B or C, you could downcast 'a' to B or C (check using instanceof to see what the type of 'a' is).

You can define two versions of dmethod() as per your question, one that takes in a B and one that take in a C. Overloading supports this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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