Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why multiple instances of Method object are for the inherited methods

I discovered that classes with default equals method has different instances of meta object Method. Why is it so? At first glance it looks not optimal because method objects are immutable.

class X {}
Method defaultM = Object.class.getMethod("equals", Object.class)
Method xMethod =  X.class.getMethod("equals", Object.class)

xMethod != defaultM
xMethod.equals(defaultM)
like image 905
Daniil Iaitskov Avatar asked Jun 17 '16 09:06

Daniil Iaitskov


People also ask

Why is multiple inheritance required?

Multiple inheritance is useful when a subclass needs to combine multiple contracts and inherit some, or all, of the implementation of those contracts. For example, the AmericanStudent class needs to inherit from both the Student class and the American class. But multiple inheritance imposes additional difficulties.

Why multiple inheritance is used in Java?

The Java programming language supports multiple inheritance of type, which is the ability of a class to implement more than one interface. An object can have multiple types: the type of its own class and the types of all the interfaces that the class implements.

Can an object inherit from multiple classes?

Multiple Inheritance is a feature of C++ where a class can inherit from more than one classes. The constructors of inherited classes are called in the same order in which they are inherited.


1 Answers

Unfortunately, Method objects are not immutable. Since Java 2, Method extends AccessibleObject, which has the setAccessible(boolean) method.

So not only do methods have a mutable property, this flag has security impacts which disallow sharing of Method objects.

Note that under the hood, Method objects do share their common immutable state via a delegate object, so what you get from Class.getMethod is just a cheap front-end object consisting of that mutable flag and a reference to the shared canonical method representation.

like image 127
Holger Avatar answered Sep 28 '22 02:09

Holger