How do I call a method using a variable? - java

SubArray = Key.Ikey;
Ikey being the variable which holds the name of the method.
I tried:
SubArray = Key.(this.IKey);
but the compiler gave the error identifier excpected.

I think you are interested in reflection. It goes something like:
method = object.getClass().getMethod(methodName, param1.class, param2.class, ..);
So you are calling the method specified by the variable 'methodName' of the object 'object'
You can read more here Reflection
and in this tutorial link

Related

How to call method of a unknown object

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...

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();

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.

Java/Android Get Parent Instance For Invoking Method

I have a method which I am trying to call dynamically. That method has an argument 'stringValue'. The method I am trying to invoke is in the parent (receivers??) class.
I can't figure out how to get the reference back to the parent
java.lang.reflect.Method method;
method = Class.forName("com.blah.MyActivity").getMethod("myFunction", String.class);
method.invoke(this,stringValue);
Gives the error:
'Message expected receiver of type com.blah.MyActivity, but got com.blah.MyActivity$SubTask'
I suspect you want:
method.invoke(MyActivity.this, stringValue);
The MyActivity.this part is the way of getting to the enclosing instance of MyActivity.
See section 15.8.4 of the JLS for more details.

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