14章类型信息-之类型转换前先做检查--之instanceof

instanceof用法:

对于instanceof有比较严格的限制,只可将其与命名类型进行比较,而不能与class对象做比较。

理解:这里所说的就是像if(pet instanceof Mutt)
counter.count("Mutt");这里的Mutt,不能用对象比较,只能用类名,比如(Mutt mutt = new Mutt()然后用mutt)或者 Mutt.class就不行了,

实例代码:

实体类父类:

//: typeinfo/pets/Individual.java
package typeinfo.pets;


public class Individual implements Comparable<Individual> {
private static long counter = 0;
private final long id = counter++;
private String name;
public Individual(String name) { this.name = name; }
// 'name' is optional:
public Individual() {}
public String toString() {
return getClass().getSimpleName() +
(name == null ? "" : " " + name);
}
public long id() { return id; }
public boolean equals(Object o) {
return o instanceof Individual &&
id == ((Individual)o).id;
}
public int hashCode() {
int result = 17;
if(name != null)
result = 37 * result + name.hashCode();
result = 37 * result + (int)id;
return result;
}
public int compareTo(Individual arg) {
// Compare by class name first:
String first = getClass().getSimpleName();
String argFirst = arg.getClass().getSimpleName();
int firstCompare = first.compareTo(argFirst);
if(firstCompare != 0)
return firstCompare;
if(name != null && arg.name != null) {
int secondCompare = name.compareTo(arg.name);
if(secondCompare != 0)
return secondCompare;
}
return (arg.id < id ? -1 : (arg.id == id ? 0 : 1));
}
} ///:~

继承类:

//: typeinfo/pets/Cat.java
package typeinfo.pets;


public class Cat extends Pet {
public Cat(String name) { super(name); }
public Cat() { super(); }
} ///:~

 

//: typeinfo/pets/Dog.java
package typeinfo.pets;


public class Dog extends Pet {
public Dog(String name) { super(name); }
public Dog() { super(); }
} ///:~

 

//: typeinfo/pets/Rodent.java
package typeinfo.pets;


public class Rodent extends Pet {
public Rodent(String name) { super(name); }
public Rodent() { super(); }
} ///:~

创建宠物的抽象类:

//: typeinfo/pets/PetCreator.java
// Creates random sequences of Pets.
package typeinfo.pets;
import java.util.*;


public abstract class PetCreator {
private Random rand = new Random(47);
// The List of the different types of Pet to create:
public abstract List<Class<? extends Pet>> types();
public Pet randomPet() { // Create one random Pet
int n = rand.nextInt(types().size());
try {
return types().get(n).newInstance();
} catch(InstantiationException e) {
throw new RuntimeException(e);
} catch(IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public Pet[] createArray(int size) {
Pet[] result = new Pet[size];
for(int i = 0; i < size; i++)
result[i] = randomPet();
return result;
}
public ArrayList<Pet> arrayList(int size) {
ArrayList<Pet> result = new ArrayList<Pet>();
Collections.addAll(result, createArray(size));
return result;
}
} ///:~

实现(创建宠物抽象类)的实现类:

//: typeinfo/pets/ForNameCreator.java
package typeinfo.pets;
import java.util.*;


public class ForNameCreator extends PetCreator {

private static List<Class<? extends Pet>> types =
new ArrayList<Class<? extends Pet>>();
// Types that you want to be randomly created:
private static String[] typeNames = {
"typeinfo.pets.Cat",
"typeinfo.pets.Dog",
"typeinfo.pets.Rodent"
};
@SuppressWarnings("unchecked")
private static void loader() {
try {
for(String name : typeNames)
types.add(
(Class<? extends Pet>)Class.forName(name));
} catch(ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
static { loader(); }
public List<Class<? extends Pet>> types() {return types;}
} ///:~

用于计算各个宠物个数的类:

package typeinfo.pets;


//: typeinfo/PetCount.java
// Using instanceof.
import typeinfo.pets.*;
import java.util.*;
import static net.mindview.util.Print.*;


public class PetCount {
static class PetCounter extends HashMap<String,Integer> {
public void count(String type) {
Integer quantity = get(type);
if(quantity == null)
put(type, 1);
else
put(type, quantity + 1);
}
}
public static void countPets(PetCreator creator) {
PetCounter counter= new PetCounter();
for(Pet pet : creator.createArray(20)) {
// List each individual pet:
printnb(pet.getClass().getSimpleName() + " ");
if(pet instanceof Pet)
counter.count("Pet");
if(pet instanceof Dog)
counter.count("Dog");
if(pet instanceof Cat)
counter.count("Cat");
if(pet instanceof Rodent)
counter.count("Rodent");
}
// Show the counts:
print();
print(counter);
}
public static void main(String[] args) {
countPets(new ForNameCreator());
}
}

//测试打印:Rodent Rodent Dog Rodent Dog Rodent Dog Rodent Cat Dog Cat Cat Cat Dog Rodent Dog Dog Dog Rodent Dog
//{Cat=4, Pet=20, Dog=9, Rodent=7}

工具类:

//: net/mindview/util/Print.java
// Print methods that can be used without
// qualifiers, using Java SE5 static imports:
package net.mindview.util;
import java.io.*;


public class Print {
// Print with a newline:
public static void print(Object obj) {
System.out.println(obj);
}
// Print a newline by itself:
public static void print() {
System.out.println();
}
// Print with no line break:
public static void printnb(Object obj) {
System.out.print(obj);
}
// The new Java SE5 printf() (from C):
public static PrintStream
printf(String format, Object... args) {
return System.out.printf(format, args);
}
} ///:~

 

你可能感兴趣的:(instanceof)