MichaelR
MichaelR

Reputation: 999

how to go from String to method

I hope the title was understandable .

I have 4 functions :

public void seta1(...);

public void seta2(...);

public void seta3(...);

public void seta4(...);

Now the user gives me a String with the methods partial name ( say String input = "a1"). Is there a way ( without using case option) to activate the correct method ?

something like : (set+input)();

Upvotes: 1

Views: 123

Answers (4)

Arnaud Denoyelle
Arnaud Denoyelle

Reputation: 31225

Introspection is intended for that purpose (see Introspector).

//Here, I use Introspection to get the properties of the class.
PropertyDescriptor[] props = Introspector.getBeanInfo(YourClass.class).getPropertyDescriptors();

for(PropertyDescriptor p:props){
    //Among the properties, I want to get the one which name is a1.
    if(p.getName().equals("a1")){
        Method method  = p.getWriteMethod();
        //Now, you can execute the method by reflection.
    }
}

Note that Introspection and Reflection are 2 different things.

Upvotes: 2

Sam
Sam

Reputation: 131

though it is little odd, possible with reflection. Try out http://docs.oracle.com/javase/tutorial/reflect/member/methodInvocation.html

Upvotes: 0

Juvanis
Juvanis

Reputation: 25950

Assuming you handle the possible exceptions, you can use Java Reflection API:

Method method = obj.getClass().getMethod("set" + "a1");
method.invoke(obj, arg1,...);

Upvotes: 3

Josh M
Josh M

Reputation: 11937

You could use reflection:

public void invoke(final String suffix, final Object... args) throws Exception{
    getClass().getDeclaredMethod("set" + suffix, argTypes(args)).invoke(this, args);
}

private Class[] argTypes(final Object... args){
    final Class[] types = new Class[args.length];
    for(int i = 0; i < types.length; i++)
        types[i] = args[i].getClass();
    return types;
}

Upvotes: 1

Related Questions