How to call method of a unknown object - java

I want to do something different with java reflection. The program i written to add global listeners to java components when applets are opened from browser. An event fired and i get event source object. Here i don't know the actual class name that object referring to.
if(object.getClass.getName().contains("oracle.ewt.laf.basic.BasicTabBarUI$Menu"))
{
// here we can invoke methods,fields,etc using reflection
}
I can call the methods of BasicTabBarUI$Menu class with reflection.
Suppose now i have the following lines with me in the above if block
LWMenuItem menuItem = (LWMenuItem)object;
menuItem.getLabel());
I don't want to specify LWMenuItem class name , instead i want to call its method getLabel(). If we know the class name , we can do as above. But how can we do same with reflection. How can we do casting in reflection?

You don't need to do casting, except of the result of calling the method. Just use the object's Class object, which has a getMethod method that will return a Method object for the method you want, then invoke it:
Class cls = object.getClass();
Method getLabel = cls.getMethod("getLabel", null);
String label = (String)getLabel.invoke(object, null);

You can continue working with the basic object when using the return value from getLabel():
Method getLabelMethod = object.getClass().getMethod("getLabel");
Object menuItem = getLabelMethod.invoke(object);
menuItem.getClass().getMethod("getName").invoke(menuItem); // or whatever...

Related

Can we cast a object into a class type whose name is only known?

I have to dynamically fetch the tables whose names are available in dropdown in a jsp. Upon the selection of table name corresponding columns should be printed. For that I was running a loop in jsp and trying but is it possible to cast an object of "Object" type into a class whose class name is only known and after that using that object I have to acesss the corresponding class methods.
ex: className I got from jsp is "Book" and I have a class Book.class which has a method getName() so something like this is what I wanted:
Object obj1 = Class.forName(className).cast(obj);
obj1.getName();
Here obj is the object I have got through session.
forName takes a String and you can't call getMethod on Object because there is no such method. Ideally you'd have an interface defining the method that's common in all the types you can select from your drop down.
If that is not an option, then there is an uglier option using reflection where you don't actually need to know the type in advance:
Class<?> clazz = Class.forName("Book");
// Object obj1 = clazz.cast(obj);
// The method getName() is undefined for the type Object
Method m = clazz.getMethod("getName");
String res = (String) m.invoke(obj);
I'd not recommend using this code as is in any production application though. You'll need quite a bit of validation and exception handling in order to make this work safely.
Yes you can do that but the object must belong to that class or some of its child class else it will give you a ClassCastException. You also need to pass complete path of that class mean fully qualified class name with package.
Object obj1 = Class.forName(com.Book).cast(obj);
obj1.getName();

Generic method calling using java reflection api

I have been trying to develop an application. A bean script will be written as per requirement which in turn will call methods (defined in the application) in various order as per requirement. The application code (apart for bean script) would not be changed.
Also, the application uses external jars which provide large number of methods - of which some are implemented in the application. However, I would like to have the possibility to use the other methods (ones that are not yet implemented) without making changes to application should the requirement arise. For this, I would like to use the Java reflection API. The user should be able to call any method present in the external jars by passing the method name and corresponding parameters (using the the external jar documentation).
I'm a java newbie so I have some code that tries to achieve it (may not be syntactically correct):
public void callExternalJarMethod(String methodName, Class[] methodParameterTypes, Object[] methodParameters)
throws NoSuchMethodException {
String className = "SampleClassName";
Class classObject = Class.forName(className);
Method methodObject;
if (methodParameterTypes.length == 0) {
methodObject = classObject.getMethod(methodName, null);
} else {
methodObject = classObject.getMethod(methodName, methodParameterTypes);
}
// Not handling calling of static methods in which case "null" would be passed instead of methodObject to the invoke method
Object returnValue = methodObject.invoke(methodObject, methodParameters);
}
I'm trying to find a way I can get the Class[] methodParameterTypes, and Object[] methodParameters populated with the relevant values. I would have the parameter types and parameter values as string. Also, any pointers towards useful utils would be appreciated.
Thanks in advance.
You are not passing an instance of SampleClassName to the Method.invoke() call here...
Object returnValue = methodObject.invoke(methodObject, methodParameters);
If the method you are going to invoke is static, you can do this...
Object returnValue = methodObject.invoke(null, methodParameters);
Otherwise (non-static), you need to create an instance of SampleClassName to execute the method on.
If the class does not need any constructor arguments, you could use...
Object returnValue = methodObject.invoke(classObject.newInstance(), methodParameters);
(Obviously there will be a load of Exceptions that you need to handle by doing "newInstance" and "invoke"...)

Java, Reflection, getting a Method from a Class

I'm having some trouble using reflection in Java. I'm attempting to save a method of a data structure but getting an error. The error is
java.lang.NoSuchMethodException: cs671.eval.SerialList.add(java.lang.Integer, java.lang.String)
The method, in this case, that I'm trying to get is the add method for a SerialList that takes a Comparable and an Object as its parameters.
structType = "cs671.eval.SerialList", keyType = "java.lang.Integer", and valType = "java.lang.String" are strings that were read in from a file.
Class dataClass = null, comparableClass = null, objectClass = null;
try{ // create data structure
dataClass = Class.forName(structType);
comparableClass = Class.forName(keyType);
objectClass = Class.forName(valType);
}
catch(ClassNotFoundException e){}
java.lang.Object structObj = null;
try{ // Create a data structure object
structObj = dataClass.newInstance();
}
catch(Exception e){}
Method m = null;
try{ // Attempt to get add method for the data structure
m = dataClass.getMethod("add", comparableClass, objectClass); // This is where it fails
}
catch(Exception e){}
Basically I'm trying to get the right method on the right datastructure with the correct classes that are going to get passed into that method but I don't know how to tell the getMethod method that those classes (comparableClass and objectClass) are the correct ones.
Thanks in advance!
Added: Here's the SerialList's add method signature
public void add(java.lang.Comparable, java.lang.Object)
You are saying -
The method, in this case, that I'm trying to get is the add method for a SerialList that takes a Comparable and an Object as its parameters.
But passing the classes - java.lang.Integer, java.lang.String.
Just a note - Only public methods are visible to getMethod() for non-publics you would have to use getDeclaredMethod() instead.
From http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Class.html#getMethod%28java.lang.String,%20java.lang.Class...%29:
To find a matching method in a class C: If C declares exactly one public method with the specified name and exactly the same formal parameter types, that is the method reflected. If more than one such method is found in C, and one of these methods has a return type that is more specific than any of the others, that method is reflected; otherwise one of the methods is chosen arbitrarily.
=> You need to pass java.lang.Comparable.class & java.lang.Object.class
Apologies for providing wrong answer earlier. Based on your comments it appears that you're trying to get a Method by avoiding to provide specific parameter types needed in the signature of that method.
If my understanding is correct then you should rather use Class#getMethods() and examine the returned Method[] for your method. Consider a skeleton code like this:
Method[] methods = dataClass.getMethods();
boolean matched = false;
// find a matching method by name
for (Method method: methods) {
Class<?>[] parameterTypes = method.getParameterTypes();
if ( "add".equals(method.getName()) && parameterTypes.length == 2 ) {
// method is your target method
// however you'll need more strict checks if there can be another add method
// in your class with 2 different parameter types
}
}
As other answers have stated, to use getMethod() you need to know and use the actual declared formal parameters of the method you are attempting to retrieve.
However, if for some reason you do not know the formal parameters at compile time, then you can iterate over all of the methods from the class until you find a method that fits your parameters (or find the most specific method that fits your parameters).
There is functionality written to do this already in apache commons bean utils, specifically in org.apache.commons.beanutils.MethodUtils.invokeMethod(...) and MethodUtils.getMatchingAccessibleMethod(...).
Source code for the above methods can be easily viewed online here.

Reflection issue of Android BluetoothService class

I want to call some methods like isEnabled(), getAddressFromObjectPath(), etc. of BluetoothService class, but this class is mark with #hide.
I know I have two possible ways to do what I want, one is remove the #hide, and the other is using reflection. I choose to use second one.
From the example of source code, I found that
Method method = Class.forName("android.os.ServiceManager").getMethod("getService", String.class);
IBinder b = (IBinder) method.invoke(null, "bluetooth");
if (b == null) {
throw new RuntimeException("Bluetooth service not available");
}
IBluetooth mBluetoothService = IBluetooth.Stub.asInterface(b);
However, what it gets is the IBluetooth not BluetoothService although BluetoothService extends IBluetooth.Stub indeed.
So my questions are as follows:
(1) Could I get the BluetoothService class by reflection just like previous example code ?
(2) If my first question is negative, I call getAddressFromObjectPath() directly by reflection method like following
Method method = Class.forName("android.server.BluetoothService").getMethod("getAddressFromObjectPath", String.class);
String b = (String) method.invoke(???, PATH);
what the object dose I need to fill in the invoke() method, BluetoothService ???
Any suggestion would be greatly appreciated !!!
After surveying on the internet, I got the answer. If I want to invoke a non-static method, I need to get the class and constructor first. Use the constructor to construct the instance and then I could invoke the non-static method by this instance.
However, I could not do that on BluetoothService class because if I do the constructor again, it would cause a lot of problem !
I decide to modify the IBluetooth.aidl to add the methods I need because BluetoothService extends IBluetooth. If I could get the IBluetooth instance, I could call the methods I need. Maybe, this is not a good solution but I think it would work.
Thanks a lot.

Utilising Javassist to provaide overloading based on return type

Ive used Javassist to dynamically change the return type of a function call, but its not working.
Ive got a call that is defined in the source code as simply:
Boolean getResult(){return true;}
But then at run time I dynamically change it to:
String getResult(){return "true"}
I then call it as:
Object o = myobject.getResult();
And get a MethodNotFound exception. If I use reflection I can see my new method on the object, but the call is failing, apparently because its somehow bound to the old return type.
If I call the new method reflectively (slight pseudocode..):
Method m = myobject.getClass.GetDeclaredMethods().(...find method named GetResult...)
Object o = m.invoke(myObject);
Then all works fine, and I can switch between manipulated and non manipulated byte code without issue, and I can see that the type of O is either String or Boolean accordingly.
Any ideas why?

Categories

Resources