I have the ability to run code that lets me make calculations and/or get variable information from a program. However I do not have access to the base code, and wondering if there is a way to print out all the methods an Object has available (public)?
Example the Class Shape, with sub classes of Circle and Square. If I was able to print out methods to Circle I would possibly see:
.getRadius()
.setRadius(newValue)
but Square would have
.getSide()
.setSide(newValue)
I have a myObject, where I know I can get
myObject[1].GetLength()
myObject[1].getDimUom()
myObject[1].getQuantity().getValue()
However I am unaware of what I can set only certain things like (by trial and error)
myObject[1].setClass(newValue)
So I would like to be able to find a way to print out the method names from an Object; again without any ability to see or modify base code (like adding reflection)
CodePudding user response:
What you basically want is to brake the information hiding principle which is the most fundamental principle in OOP.
What You (most likely) really want is to define a common behavior that could be implemented by the subclasses in their specific way. Regarding your example this could be a method changeSizeTo(int newValue)
defined in an interface that would be implemented by your classes and each class would do something specific.
[update]
I mean anything available to public is it really hiding? – Edward
The point is not about the actual access modifiers but the question: "Does this force the caller to know what subclass this object actually is?"
CodePudding user response:
Solution
You can use reflection.
Class clazz = circle.getRadius().getClass();
Method[] methods = clazz.getMethods();
for ( Method method : methods ) {
System.out.println( method.getName() );
}
With that said, you should listen to the advice given by @Timothy Truckle. You most likely have a design problem if you need to use this, assuming you aren't writing a framework or a library