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();
}
}
Ingo R. Homann - 27 Jun 2007 15:20 GMT
Hi,
> public class dynamicloader {
> ...
[quoted text clipped - 5 lines]
> 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
Tom Hawtin - 27 Jun 2007 15:26 GMT
> 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
printdude1968@gmail.com - 27 Jun 2007 16:27 GMT
> jan.reb...@gmail.com wrote:
> > I have the following code. The problem is it always display a null
[quoted text clipped - 10 lines]
>
> Tom Hawtin
OMG... is this "self modifying code"?