简体   繁体   中英

Java generic type for objects

In Objective-C we have a generic type for objects called "id".

id someObject = someValue;
if([someObject isKindOfClass:[NSString class]]) {
    NSString *string = someObject;
}

I want to know if there's something like that in Java.

id someObject = someValue;
if(someObject instanceof String) {
    String string = someObject;
}

Unless I'm missing something, you were very close to the answer yourself:

// 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;
}

As a side note, all object instances contain information about the object's class: someObject.getClass()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM