How to dynamically edit a method

J

jan.rebada

I have the following code. The problem is it always display a null
value. It will not successfully set the Name. THanks.

import java.lang.reflect.Method;


public class dynamicloader {

private String name = "";


public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public void load() {
Class c = this.getClass();
Object newobj = null;
try {
newobj = c.newInstance();
} catch (Exception e) {
System.out.println(e);
}

try {
Method m = c.getMethod("setName", new Class[]{String.class});
String result = (String) m.invoke(newobj,new Object[]{"My name"});
System.out.println("Result: " + result);
} catch (Exception e) {
System.out.println(e);
}
}

public static void main(String[] args) {
dynamicloader dl = new dynamicloader();
dl.load();
}
}
 
I

Ingo R. Homann

Hi,

public class dynamicloader {
...
public void setName(String name) {
this.name = name;
}
...
Method m = c.getMethod("setName", new Class[]{String.class});
String result = (String) m.invoke(newobj,new Object[]{"My name"});
System.out.println("Result: " + result);

Take a look at your code again (I snipped everything except the
important lines) and think about it.

What do you expect?

Hint: What is the return type of the method you are invoking?

Ciao,
Ingo
 
T

Tom Hawtin

I have the following code. The problem is it always display a null
value. It will not successfully set the Name. THanks.
public void setName(String name) {
Method m = c.getMethod("setName", new Class[]{String.class});
String result = (String) m.invoke(newobj,new Object[]{"My name"});
System.out.println("Result: " + result);

You have displayed the return value from setName. setName does not
return a value.

Reflection is confusing and error-prone. It's best avoided.

Tom Hawtin
 
P

printdude1968

I have the following code. The problem is it always display a null
value. It will not successfully set the Name. THanks.
public void setName(String name) {
Method m = c.getMethod("setName", new Class[]{String.class});
String result = (String) m.invoke(newobj,new Object[]{"My name"});
System.out.println("Result: " + result);

You have displayed the return value from setName. setName does not
return a value.

Reflection is confusing and error-prone. It's best avoided.

Tom Hawtin

OMG... is this "self modifying code"?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top