Re: Call Method by String
I quickly threw this together it's a bit messed up but seems to do what you want
Code:
import java.lang.reflect.*;
public class EditCanvas{
public EditCanvas(){
try {
Method m = this.getClass().getDeclaredMethod("printit",(Class[])null);
try {
m.invoke(this,(Object[])null);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void printit(){
System.out.println("test");
}
public static void main(String[] args) {
EditCanvas c = new EditCanvas();
}
}
Re: Call Method by String
All that isn't necessary.
Code:
public class methodCalling
{
public void methodOne()
{
System.out.println("Hello, world!");
}
public void methodTwo()
{
//Call 'methodOne'
methodOne();
}
}
Tried and tested it, it does exactly what you want.
Re: Call Method by String
He doesn't want to call the method the normal way. He wants to use a string value to call the method by name.
Re: Call Method by String
Reflection is your friend ;)
Re: Call Method by String
Cheers DeadEyes, haven't been able to test it out yet because im away for the weekend, but it looks exaclty like what i want.
Thanks