Java我如何知道对象的类?
例如,您在一个对象中有一个List对象集合,并且您想要基于该对象的类执行一些逻辑。使用instanceof运算符可以轻松完成此操作。true如果对象是指定类的实例,则运算符返回,否则返回false。
在instanceof实现一个操作者时是最有可能使用equals(Objecto)的对象的方法,以检查是否相比对象是同一类。
package org.nhooo.example.lang;
import java.util.ArrayList;
import java.util.List;
public class InstanceOfExample {
public static void main(String[] args) {
Person p = new Person("John");
Animal a = new Animal("Highland");
Thing t = new Thing("Red");
String text = "hello";
Integer number = 1000;
List list = new ArrayList();
list.add(p);
list.add(a);
list.add(t);
list.add(text);
list.add(number);
for (int i = 0; i < list.size(); i++) {
Object o = list.get(i);
if (o instanceof Person) {
System.out.println("My name is " + ((Person) o).getName());
} else if (o instanceof Animal) {
System.out.println("I live in " + ((Animal) o).getHabitat());
} else if (o instanceof Thing) {
System.out.println("My color is " + ((Thing) o).getColor());
} else if (o instanceof String) {
System.out.println("My text is " + o.toString());
} else if (o instanceof Integer) {
System.out.println("My value is " + ((Integer) o));
}
}
}
}
class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
class Animal {
private String habitat;
public Animal(String habitat) {
this.habitat = habitat;
}
public String getHabitat() {
return habitat;
}
}
class Thing {
private String color;
public Thing(String color) {
this.color = color;
}
public String getColor() {
return color;
}
}上面的代码片段的结果:
My name is John I live in Highland My color is Red My text is hello My value is 1000
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短