Java 将instanceof与类对象一起使用
正确的语法是什么Java 将instanceof与类对象一起使用,java,class,methods,instanceof,Java,Class,Methods,Instanceof,正确的语法是什么 public boolean isTypeOf(Class type) { return this instanceof type; } 我打算称之为: foo.isTypeOf(MyClass.class); 该方法将被重写,否则我将只在原地使用instanceof。使用: 此方法确定给定参数是否为类的实例。如果对象是该类的子类,则此方法也将起作用 引用Javadoc: 此方法是Java语言instanceof运算符的动态等价物 this.getClass().
public boolean isTypeOf(Class type) {
return this instanceof type;
}
我打算称之为:
foo.isTypeOf(MyClass.class);
该方法将被重写,否则我将只在原地使用instanceof
。使用:
此方法确定给定参数是否为类的实例。如果对象是该类的子类,则此方法也将起作用
引用Javadoc:
此方法是Java语言instanceof
运算符的动态等价物
this.getClass().equals(type)
?您知道Class.isInstance(Object)吗请注意,在Java语法中,类的实例不是类型名,而是一个值,即使使用泛型(例如,在泛型函数中,如果(someObject instanceof t),也无法从值中获取类型名。
public boolean isTypeOf(Class type) {
return type.isInstance(this);
}