Natan Griefwell
Natan Griefwell

Reputation: 91

Getting method via reflection

My previous post was not very clear, sorry for that. I will try to give a better example of what I am trying to do.

I have an Java application that will load .class files and runs them in a special enviroment (the Java app has built-in functions) Note: This is not a library.

That Java application will then display an applet, and I want to modify the variables in the applet.

The main class of the applet is called 'client'. The Java application will load the applet by creating an new instance of class 'client'.

I already got access to the 'client' class. the Java application will put the applet in a variable:

Applet client = (Applet) loadedClientClass.newInstance();

So I did this:

Class<?> class_client = client.getClass();

I can now read and set the fields but the 'client' class will call a funation of an other class, like this:

otherClass.someVoid(false);

And if I try something like:

class_client.getDeclaredMethod("otherClass.someVoid",boolean.class);

It will fail, saying that the function can not be found.

'otherClass' is the direct class name, it is not a reference to a new instance of the class as far as I know.

Is there any way to get 'otherClass.someVoid'?

Upvotes: 0

Views: 159

Answers (3)

Bohemian
Bohemian

Reputation: 424983

You're using getDeclaredMethod like a static method (expecting it to return methods from any class), but it only returns method from the class itself. Here's how you can call otherClass.someVoid(false).

Class<?> otherClass = Class.forName("com.xyz.OtherClass"); // Get the class
Method method = otherClass.getDeclaredMethod("someVoid", boolean.class);

// If the method is an Class (ie static) method, invoke it on the Class:
method.invoke(otherClass, false);

// If the method is an instance (ie non-static) method, invoke it on an instance of the Class:
Object otherInstance = otherClass.newInstance(); // Get an instance of other class - this approach assumes there is a default constructor
method.invoke(otherInstance, false);

Upvotes: 1

Nivas
Nivas

Reputation: 18344

Is there any way to change 'otherClass.someInteger' through the 'mainClass' class?

No.

But you can get it via OtherClass' class via Class.forName:

Class<?> theOtherClazz = Class.forName("OtherClass");

And then get the methods via theOtherClazz.getDeclaredMethod

Upvotes: 0

Jon7
Jon7

Reputation: 7215

If the class isn't initialized, the var someInteger doesn't exist. It's a member variable, so it only exists inside of instances of the class. So, you can't change it since it's doesn't exist. Now, if you made it a static variable, then you could change it.

Upvotes: 0

Related Questions