IAd*_*ter 769
if (obj instanceof C) {
//your code
}
Run Code Online (Sandbox Code Playgroud)
icz*_*cza 165
提出了多个正确的答案,但还有更多的方法:Class.isAssignableFrom()并且只是试图转换对象(可能会抛出一个ClassCastException).
让我们总结一下测试对象obj是否是类型实例的可能方法C:
// Method #1
if (obj instanceof C)
;
// Method #2
if (C.class.isInstance(obj))
;
// Method #3
if (C.class.isAssignableFrom(obj.getClass()))
;
// Method #4
try {
C c = (C) obj;
// No exception: obj is of type C or IT MIGHT BE NULL!
} catch (ClassCastException e) {
}
// Method #5
try {
C c = C.class.cast(obj);
// No exception: obj is of type C or IT MIGHT BE NULL!
} catch (ClassCastException e) {
}
Run Code Online (Sandbox Code Playgroud)
null处理上的差异null但处理方式有所不同:
false,如果obj是null(null不是任何实例).NullPointerException显然会抛出.null因为null可以投射到任何类型!要记住:
null不是任何类型的实例,但它可以转换为任何类型.
Class.getName()不应该用来执行"is-instance-of"测试,因为如果对象不是类型C而是它的子类,它可能有一个完全不同的名称和包(因此类名显然不匹配)但它是仍然是类型C.Class.isAssignableFrom()是不是对称的:obj.getClass().isAssignableFrom(C.class)将返回false如果类型obj是一个子类C.Joh*_*iss 31
您可以使用:
Object instance = new SomeClass();
instance.getClass().getName(); //will return the name (as String) (== "SomeClass")
instance.getClass(); //will return the SomeClass' Class object
Run Code Online (Sandbox Code Playgroud)
HTH.但我认为大多数时候,将它用于控制流程或类似的东西是不好的做法......
Yuv*_*dam 24
使用任何建议的方法都被认为是基于不良OO设计的代码气味.
如果你的设计很好,你不应该发现自己需要使用getClass()或instanceof.
任何建议的方法都可以做到,但在设计方面需要牢记.
小智 15
在这种情况下我们可以使用反射
objectName.getClass().getName();
Run Code Online (Sandbox Code Playgroud)
例:-
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getClass().getName();
}Run Code Online (Sandbox Code Playgroud)
在这种情况下,您将获得对象传递给HttpServletRequest接口引用变量的类的名称.
And*_*son 13
.isInstance" Class"类上还有一个方法.如果你通过你得到一个对象的类,myBanana.getClass()你可以看到你的对象myApple是否是与myBananavia 相同的类的实例
myBanana.getClass().isInstance(myApple)
Run Code Online (Sandbox Code Playgroud)