Cách sử dụng toán tử InstanceOf trong Java

Đôi khi chúng ta cần phải biết loại dữ liệu nào một đối tượng là: Bài học này sẽ giải thích từ khóa instanceof trong Java và cung cấp các thí dụ mã về cách dùng và hàm của nó.

 

Tôi là ai?

Có những lúc chúng ta cần phải biết loại dữ liệu nà một đối tượng cụ thể, hoặc nếu một đối tượng là một loại khăng khăng (ví dụ: nếu Apple là một loại Pie hoặc Tree). Từ khóa instanceof của Java được sử dụng cho các thử nghiệm này; nó so sánh đối tượng với một kiểu nhất thiết. Instanceof chỉ trả về TRUE hoặc FALSE.

Nó giúp xem mã hoạt động, bởi thế hãy coi xét một số kiểu dáng để chúng tôi có thể thấy từ khóa này được sử dụng như thế nào. Dưới đây là ví dụ về từ khóa. Chúng ta đã khai báo một đối tượng String, sau đó dùng instanceof để xác định xem đối tượng có phải là một chuỗi hay không.

  1. public static void main(String[] args)
  2.   String what = "What Am I?";
  3.   if(what instanceof java.lang.String)
  4.    System.out.println(what = " is a String");
  5.  

 

And the output:

An Important Note About a Null Value!

 

If the variable or object is NULL (no value), instanceof will return FALSE. It doesn't matter if the variable is really an instance of a Pie; if it has somehow been changed to NULL, your test will fail.

 

Here's another useful test for instanceof. Let's say we created an array of Strings instead of a standard String. The object is no longer a String and instanceof will return false. If we want to check if an object is a String array, we can use the keyword as follows:

 

  1. public static void main(String[] args)
  2.   String[] myString =
  3.    "Seven",
  4.    "Eight",
  5.    "Nine"
  6.  
  7.   if(myString instanceof String[])
  8.    System.out.println("Object is String Array&quot);
  9.  

 

And the output:

 

Object Testing

 

Now, it's pretty obvious that our object is a String! But remember that Java is object-oriented, and instanceof can be very helpful when testing our own classes.

 

Let's say we have a class called Rhubarb and we create a new instance of it. To check if the class is really an instance of Rhubarb, we can use the following:

 

  1. Rhubarb r = new Rhubar();
  2. if(r instanceof Rhubarb)
  3.   //true

 

For the most part, you will know that Rhubarb is an object of type Pie. But what about Birch? Is it a child class of Tree or BoysName? Below is a snippet from a Java program, that checks to make sure that Raptor is really an object of the Dinosaur class (as opposed to a vehicle or some other class).

 

  1. System.out.println(raptor instanceof Dinosaur);

Another use for instanceof is when we are downcasting objects.

And the output:

SHARE

Milan Tomic

  • Image
  • Image
  • Image
  • Image
  • Image
    Blogger Comment
    Facebook Comment

0 nhận xét:

Đăng nhận xét