简体   繁体   中英

Java Object.class and x.getClass

I have a method like this:

public Object load(Object type) {
...
}

Note that the parameter is an Object-type.

I have several classes that are using the loadConfiguration method. Inside the method I need to know the class, so the value for MyObject.class is needed. Well, because I have an Object , this is not possible and type.getClass() also throws an exception, because is just gives me java.lang.Class and not the real one. One possibility would be to use instanceof functionality but I would like to keep it as general as possible.

Any ideas for this? I also had look to this topic .

Thank You!

I'm not sure in your example exactly what is going on. I believe in your example the parameter type is a Class object, so you can just cast it.

public Object load(Object type) {
Class<?> clazz = (Class<?>)type;
...
}

Calling code would then look like

blah.load(MyObject.class);

If in fact you need to know the class of the type the method is being invoked on, you can simply call

Class<?> clazz = this.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