在Objective-C中,我们有一个名为" id"。
的对象的泛型类型id someObject = someValue;
if([someObject isKindOfClass:[NSString class]]) {
NSString *string = someObject;
}
我想知道Java中是否有类似的内容。
id someObject = someValue;
if(someObject instanceof String) {
String string = someObject;
}
答案 0 :(得分:3)
除非我错过了什么,否则你自己非常接近答案:
// obtain your object from somewhere
Object someObject = obtainObjectInstance();
// if it's a string...
if(someObject instanceof String) {
// cast and assign to some variable
String string = (String)someObject;
}
作为旁注,所有对象实例都包含有关对象类的信息:someObject.getClass()