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 周一祝福语简短精辟