简体   繁体   中英

Get method from Class then invoke via Object

In order to invoke a method on a object via reflection, the only way I know how to do it is like so:

Object o = ...;
Method m = o.getClass().getMethod("methodName",null);
Object x = m.invoke(o,null);

Why doesn't Java have a getMethods method in the Object class? (As well as getSuperClass, getFields, etc, etc).

So we could just do something like:

Object x = o.invoke("methodName",null);

Why not? I assume this is for performance reasons.

(Also as a side note. In English, it makes more sense to say 'subject invokes object', so that would be in programming terms, object invoke method. But with Java we get 'method invoke on object'. Glad I could confuse you today.)

I believe the reason is that java.lang.Object is supposed to serve as the root of the class hierarchy and any method on it should pertain to instances of that object rather than the concept of an object.

Adding reflection utility methods to Object would spoil this. You'd have a choice of calling o.myMethod() or o.invoke("myMethod", null) and this would introduce a style of programming in Java that is not compile-safe, in that there is no compile-time guarantee that "myMethod" exists in the latter. This would make it very easy for developers to do away with type safety and just use .invoke all the time without bothering to consider proper object-oriented design.

By forcing developers to explicitly ask for an instance of Class , we maintain this separation between the reflection API and "concrete" Java. So, while it can sometimes be a pain, it's good to encourage developers to code properly. Also, it means that the OOP concept of an object is represented by java.lang.Object and the concept of a class is represented by java.lang.Class , which is a nice, clear distinction of responsibility.

The class Object

is the root of the class hierarchy.

It describes behavior that every class will need.

Any additional behavior is described by the sub classes, but a sub class doesn't necessarily have to have behavior. You can declare a class of constants, an enum , or even an array. Then it wouldn't make sense to have an invoke method on those.

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