Rtti check in front of Java styling

Source: Internet
Author: User
Tags count tostring

To date, the Rtti forms we have known include:
(1) classic styling, such as "(Shape)", which uses RTTI to ensure the correctness of the styling and creates a classcastexception violation after encountering a failed shape. The
(2) Represents the class object of the object type. You can query the class object to get useful run-time data.

in C + +, classic "(Shape)" Styling does not perform rtti. It simply tells the compiler to treat the object as a new type. and Java performs type checking, which is often called the "type-safe" look-back styling. The reason is called "the next Model", is due to the hierarchical structure of the way the historical arrangement caused. If a circle (circle) is shaped to a shape (geometric shape), it is called the tracing shape, because the circle is only a subset of the geometry. Conversely, if shape shape to circle, it is called the next shape. However, although we know clearly that circle is also a shape, the compiler can automatically trace the shape, but it does not guarantee that a shape must be a circle. Therefore, the compiler does not allow automatic tracing, unless the shape is explicitly specified once. The
Rtti exists in three different forms in Java. The keyword instanceof tells us whether the object is an instance of a particular type (instance or "instance"). It returns a Boolean value, to use in the form of a problem, as follows:
if (x instanceof Dog)
((DOG) x). Bark ();
Styling x to a DOG before the IF statement checks if object x is subordinate to the Dog class. Before styling, if there is no other information to tell you the type of object, then the use of instanceof is very important-otherwise you will get a classcastexception violation.
Our most common practice is to look for a type (such as a triangle to be purple), but the following program demonstrates how to mark all objects with instanceof.
 

: Petcount.java//Using instanceof package c11.petcount;

Import java.util.*; Class Pet {} class Dog extends Pet {} class Pug extends Dog {} class Cat extends pet {} class Rodent extends pet {} class

Gerbil extends Rodent {} class Hamster extends rodent {} class Counter {int i;} 
  public class Petcount {static string[] Typenames = {"Pet", "Dog", "Pug", "Cat", "Rodent", "Gerbil", "Hamster",
  };
    public static void Main (string[] args) {Vector pets = new vector ();
        try {class[] pettypes = {class.forname ("C11.petcount.Dog"), Class.forName ("C11.petcount.Pug"), Class.forName ("C11.petcount.Cat"), Class.forName ("C11.petcount.Rodent"), Class.forName ("C11.petcount").
      Gerbil "), Class.forName (" C11.petcount.Hamster "),}; for (int i = 0; i < i++) pets.addelement (pettypes[(int) (Math.random () *pettypes.lengt
    h)]. newinstance ()); catch (instantiationexception e) {} catch (Illegalaccessexception e) {} catch (ClassNotFoundException e) {} Hashtable h = new Hashtable ()
    ;
    for (int i = 0; i < typenames.length i++) H.put (Typenames[i], New Counter ());
      for (int i = 0; i < pets.size (); i++) {Object o = pets.elementat (i);
      if (o instanceof Pet) ((Counter) H.get ("Pet")). i++;
      if (o instanceof Dog) ((Counter) h.get ("Dog")). i++;
      if (o instanceof Pug) ((Counter) h.get ("Pug")). i++;
      if (o instanceof cat) ((Counter) h.get ("Cat")). i++;
      if (o instanceof Rodent) ((Counter) h.get ("Rodent")). i++;
      if (o instanceof Gerbil) ((Counter) h.get ("Gerbil")). i++;
    if (o instanceof Hamster) ((Counter) h.get ("Hamster")). i++;
    for (int i = 0; i < pets.size (); i++) System.out.println (Pets.elementat (i) getclass (). toString ()); for (int i = 0; i < typenames.length i++) System.out.println (Typenames[i] + "Quantity: "+ ((Counter) H.get (Typenames[i])). i); }
} ///:~

In Java 1.0, there is a small restriction on instanceof: it can only be compared to a named type and cannot be compared to a class object. In the above example, you may find it troublesome to write all those instanceof expressions. This is the case. But in Java 1.0, there is no way to automate this task-you cannot create a vector of class and compare it to it. You'll end up realizing that if you write a large number of instanceof expressions, the entire design can be problematic.
Of course, this example is just an idea-it's best to add a static data member to each type and then increment it in the builder to track the count. When you write a program, you may imagine that you have the source control of your class, and you can change it freely. However, because the actual situation is not always the case, so rtti seems particularly convenient.

1. Use the class tag
Petcount.java example to rewrite with the Java 1.1 class tag. The resulting results are more clearly understood:
 

: Petcount2.java//Using Java 1.1 class literals package c11.petcount2;

Import java.util.*; Class Pet {} class Dog extends Pet {} class Pug extends Dog {} class Cat extends pet {} class Rodent extends pet {} class

Gerbil extends Rodent {} class Hamster extends rodent {} class Counter {int i;}
    public class PetCount2 {public static void main (string[] args) {Vector pets = new vector ();
      Class[] Pettypes = {//Class literals work in Java 1.1+ Only:Pet.class, Dog.class, Pug.class,
    Cat.class, Rodent.class, Gerbil.class, Hamster.class,}; 
          try {for (int i = 0; i < i++) {//Offset by one to eliminate Pet.class:int rnd = 1 + (int) (
        Math.random () * (pettypes.length-1));
      Pets.addelement (Pettypes[rnd].newinstance ());
    The catch (Instantiationexception e) {} catch (Illegalaccessexception e) {} Hashtable h = new Hashtable (); for (int i = 0; i< Pettypes.length;
    i++) H.put (pettypes[i].tostring (), New Counter ());
      for (int i = 0; i < pets.size (); i++) {Object o = pets.elementat (i);
      if (o instanceof Pet) ((Counter) h.get ("Class C11.petcount2.Pet")). i++;
      if (o instanceof Dog) (Counter) H.get ("Class C11.petcount2.Dog")). i++;
      if (o instanceof Pug) (Counter) H.get ("Class C11.petcount2.Pug")). i++;
      if (o instanceof Cat) ((Counter) h.get ("Class C11.petcount2.Cat")). i++;
      if (o instanceof Rodent) (Counter) H.get ("Class C11.petcount2.Rodent")). i++;
      if (o instanceof Gerbil) (Counter) H.get ("Class C11.petcount2.Gerbil")). i++;
    if (o instanceof Hamster) (Counter) H.get ("Class C11.petcount2.Hamster")). i++;
    for (int i = 0; i < pets.size (); i++) System.out.println (Pets.elementat (i) getclass (). toString ()); Enumeration keys = H.keys ();
      while (Keys.hasmoreelements ()) {String nm = (String) keys.nextelement ();
      Counter cnt = (Counter) h.get (nm);
    System.out.println (nm.substring nm.lastindexof ('. ') + 1) + "Quantity:" + cnt.i); }
  }
} ///:~

Here, the Typenames (type name) array has been deleted to get the type name from the class object instead. Note the extra work for this: for example, the class name is not Getbil, but C11.petcount2.Getbil, which already contains the name of the package. Also note that the system is able to classify and interface. The
can also see that the Pettypes creation module does not need to be surrounded by a try block because it is checked at compile time and does not "throw" any violations like Class.forName ().
After the pet is created dynamically, you can see that the random numbers have been limited to between 1 and pettypes.length, and not including 0. That is because 0 represents Pet.class, and an ordinary pet object may not be of interest to anyone. However, since Pet.class is part of the pettypes, all pet (PET) is counted in the count.

2. The dynamic instanceof
Java 1.1 Adds a Isinstance method to the class class. It allows you to invoke the instanceof operator dynamically. In Java 1.0, it can only be called statically (as noted earlier). Therefore, all the annoying instanceof statements can be deleted from the Petcount example. As follows:
 

: Petcount3.java//Using Java 1.1 isinstance () package c11.petcount3;

Import java.util.*; Class Pet {} class Dog extends Pet {} class Pug extends Dog {} class Cat extends pet {} class Rodent extends pet {} class

Gerbil extends Rodent {} class Hamster extends rodent {} class Counter {int i;}
    public class PetCount3 {public static void main (string[] args) {Vector pets = new vector (); Class[] Pettypes = {pet.class, dog.class, Pug.class, Cat.class, Rodent.class, Gerbil.
    Class, Hamster.class,}; 
          try {for (int i = 0; i < i++) {//Offset by one to eliminate Pet.class:int rnd = 1 + (int) (
        Math.random () * (pettypes.length-1));
      Pets.addelement (Pettypes[rnd].newinstance ());
    The catch (Instantiationexception e) {} catch (Illegalaccessexception e) {} Hashtable h = new Hashtable (); for (int i = 0; i < pettypes.length i++) H.put (pettypes[i). toString (), New Counter ());
      for (int i = 0; i < pets.size (); i++) {Object o = pets.elementat (i);  Using isinstance to eliminate individual//instanceof expressions:for (int j = 0; j < Pettypes.length;
          ++J) if (Pettypes[j].isinstance (o)) {String key = Pettypes[j].tostring ();
        ((Counter) H.get (Key)). i++; for (int i = 0; i < pets.size (); i++) System.out.println (Pets.elementat (i). GetClass (). Tostrin
    g ());
    Enumeration keys = H.keys ();
      while (Keys.hasmoreelements ()) {String nm = (String) keys.nextelement ();
      Counter cnt = (Counter) h.get (nm);
    System.out.println (nm.substring nm.lastindexof ('. ') + 1) + "Quantity:" + cnt.i); }
  }
} ///:~

As you can see, the Java 1.1 isinstance () method has eliminated the need for instanceof expressions. In addition, this also means that once a new type of pet is required, simply change the pettypes array, without altering the remainder of the program (but is necessary when using instanceof).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.