|
-
Nov 18th, 2005, 09:17 AM
#1
Thread Starter
<?="Moderator"?>
Call Method by String
Hey I'm wondering if it is possible to call a method from a its own class by the function name or something similar
Eg
Code:
public class Xyz
{
public void foo()
{
this.cassMethodFunction("bar")
}
public void bar()
{
System.out.println("Hello World!");
}
}
-
Nov 18th, 2005, 10:18 AM
#2
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();
}
}
-
Nov 18th, 2005, 10:18 AM
#3
Fanatic Member
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.
Last edited by x-ice; Nov 18th, 2005 at 10:25 AM.
-
Nov 18th, 2005, 10:48 AM
#4
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.
-
Nov 18th, 2005, 09:27 PM
#5
Frenzied Member
Re: Call Method by String
Reflection is your friend
-
Nov 19th, 2005, 03:33 PM
#6
Thread Starter
<?="Moderator"?>
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
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|