Why when i try to invoke the method i get:
java.lang.IllegalArgumentException: object is not an instance of declaring class
My code:
Class<?> tWCCamRes = tCLSLoader.loadClass("com.github.sarxos.webcam.WebcamResolution");
Field tVGA = tWCCamRes.getDeclaredField("VGA");
Method tMeth = tVGA.getDeclaringClass().getDeclaredMethod("getSize");
tMeth.invoke(tVGA, (Object[]) null); // Error
In theory I pass the object instance but it failed.
Thanks in advance :)
You're calling the method getSize(), using reflection, on an object of type Field (tVGA), instead of calling it on the value of this field, which is of type WebcamResolution.
Assuming that you really need to do this via reflection, the code should be:
Class<?> tWCCamRes = tCLSLoader.loadClass("com.github.sarxos.webcam.WebcamResolution");
Field tVGA = tWCCamRes.getDeclaredField("VGA");
Object vgaFieldValue = tVGA.get(null); // it's a static field, so the argument of get() can be null.
Method tMeth = tVGA.getDeclaringClass().getDeclaredMethod("getSize");
tMeth.invoke(vgaFieldValue);
You invoke the getSize method on the field tVGA, but the method is declared on com.github.sarxos.webcam.WebcamResolution.
If you want to invoke an instance method you have to pass the instance as the inovke method's first argument.
If the method doesn't take an argument like com.github.sarxos.webcam.WebcamResolution.getSize()
Just invoke it this way:
tMeth.invoke(webcamResolutionObj);
But why don't you just use the WebcamResolution enum.
String enumName = "VGA";
WebcamResolution wcResolution = WebcamResolution.valueOf(enumName);
Dimension size = wcResolution.getSize();
Related
I have two classes in java. I am calling a method of 2nd class from 1st class when the 2nd class name is stored in a string variable.
I tried the below code.It creates the class.
String adapterClass = "com.appzillon.server.impl.ViewAccDtlsAdapterImpl";
Class className = Class.forName(adapterClass);
After that how to call the method.Method name is getInfo with a string type paramater.
Method method = className.getDeclaredMethod("getInfo", String.class);
method.invoke(instance, "your parameter");
Where instance is either:
Object instance = null;
if the method is static. Or:
Object instance = className.getDeclaredConstructor().newInstance();
If the method is a member method
For scenarios like these, you can very well use Java Reflection APIs.
Class classInstance = Class.forName(<your class name>);
Methoed methodHandle = classInstance.getMethod(<methodName>,<arguments classes>);
Object returnValue = methodHandle.invoke(null, "parameter-value1");
Note : The null parameter is the object you want to invoke the method on. If the method is static you supply null instead of an object instance
I have a class that is going to be passed into a function and it will be defined as follows:
class ayy{
String blah;
Class a;
Class b;
}
I want to be able to invoke the getSimpleName() method on the classes a and b. Currently I am doing it as follows:
Class c = (Class)argument; // Where argument is the "ayy" class
c.getField("a").getSimpleName();
But this gives me an error saying "getSimpleName()" is not defined for type field.
You cannot call a method directly on an object that results from reflection, such as you're doing with Field, as if it were a reference variable of the desired type.
Instead, you'll need to call getDeclaredField, because getField only gets public fields. Also, you'll need to get() the value of the Field, passing in an instance of the ayy class, which will return the value of the Field. Then you'll need to cast it to a Class, because get() returns an Object. Then you can call getSimpleName().
Class<?> classOfA = (Class<?>) c.getDeclaredField("a").get(anAyy);
String simpleName = classOfA.getSimpleName();
You'll also need to catch the various reflection-related exceptions that may be thrown.
My code looks like the following:
class MyObject {
MyField f = new MyField();
}
class MyField {
public void greatMethod();
}
Is there a way to invoke the greatMethod() using reflection on a object of the class MyObject?
I tried the following:
Field f = myObject.getClass().getDeclaredField("f");
Method myMethod = f.getDeclaringClass().getDeclaredMethod("greatMethod", new Class[]{});
myMethod.invoke(f);
But instead it is trying to call greatMethod() on my myObject directly and not on the field f in it. Is there a way to achieve this without need to modify the MyObject class (so that it would implement a method which calls the appropriate method on f).
You were close yourself, you just need to get the declared method and invoke it on the instance of the field that is containted within your object instance, instead of the field, like below
// obtain an object instance
MyObject myObjectInstance = new MyObject();
// get the field definition
Field fieldDefinition = myObjectInstance.getClass().getDeclaredField("f");
// make it accessible
fieldDefinition.setAccessible(true);
// obtain the field value from the object instance
Object fieldValue = fieldDefinition.get(myObjectInstance);
// get declared method
Method myMethod =fieldValue.getClass().getDeclaredMethod("greatMethod", new Class[]{});
// invoke method on the instance of the field from yor object instance
myMethod.invoke(fieldValue);
I'm not sure how "getDeclaredMethod" works in java, can some one explain how to get the value from the method, this is what i have..
I want to get this value (body_number), which is in the AIBody Class.
public int getBody_number() {
return body_number;
}
And in the same class i have this
Method m = body_A.getUserData().getClass().getDeclaredMethod("getBody_number", null);
How would i get the "body_number" value from m?
ps getUserData is a class of the object that i want to get the method answer out of
Any help would be great.
Adam
Since m is an instance method of whatever object is returned by body_A.getUserData() and it takes no arguments, you'd do something like this:
Method m = body_A.getUserData().getClass().getDeclaredMethod(
"getBody_number", null
);
int val = (Integer) m.invoke(body_A.getUserData());
(You'll have to wrap it in a try/catch or declare the appropriate throws in the method in which this code executes.)
Of course, once you have the Method object, you are not limited to invoking it for the object returned by body_A.getUserData(); you can pass it any instance of AIBody.
Reference: Method.invoke() doc
However, I have to agree with what Bhaskar wrote: why are you using reflection for this? You can simply call:
int val = body_A.getUserData().getBody_number();
You get back an instance of java.lang.reflect.Method, on which you use the invoke method
int val = ((Integer)m.invoke(body_A.getUserData())).intValue()
You may want to consider why you are using reflection in this case and not just
body_A.getUserData().getBody_number()
How do I invoke a method (e.g. setter inside object class) on an already existing object using Java reflection?
You have a great tutorial HERE.
Here is a way:
Object yourObject = ...;
Class clazz = yourObject.getClass();
Method setter = clazz.getMethod("setString", String.class); // You need to specify the parameter types
Object[] params = new Object[]{"New String"};
setter.invoke(this, params); // 'this' represents the class from were you calling that method.
// If you have a static method you can pass 'null' instead.
See the Reflection Trail.
You can do this,
Class cls = obj.getClass();
Method m = cls.getMethod("yourMethod", String.class); // assuming there is a method of signature yourMethod(String x);
m.invoke(obj, "strValue");