1

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)();

MichaelR
  • 841
  • 11
  • 31

4 Answers4

3

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

Method method = obj.getClass().getMethod("set" + "a1");
method.invoke(obj, arg1,...);
Juvanis
  • 25,000
  • 3
  • 61
  • 84
  • `(...)` signifies that his method takes arguments, this code does not account for the possible arguments. – Josh M Aug 28 '13 at 17:42
  • Your code will fail if there are args because you try are trying to invoke the methods with args but when you get the method, you don't specify the arg classes. Therefore, your code is invalid. – Josh M Aug 28 '13 at 17:49
  • 1
    @JoshM The code is for just giving an idea, not solving the problem exactly, it is up to OP. – Juvanis Aug 28 '13 at 20:30
2

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.

Arnaud Denoyelle
  • 25,847
  • 10
  • 73
  • 128
  • No, they aren't. Introspection uses reflection under the hood. – Eric Stein Aug 28 '13 at 17:55
  • Conceptually, they are different but you are right, from the point of view of dependencies, Introspection is strongly linked to Reflection. – Arnaud Denoyelle Aug 28 '13 at 17:59
  • There is a difference: [Why is reflection called reflection instead of introspection?](http://stackoverflow.com/questions/351577/why-is-reflection-called-reflection-instead-of-introspection) but it's more like introspection is part of reflection. – zapl Aug 28 '13 at 18:00
1

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;
}
Josh M
  • 10,457
  • 7
  • 37
  • 46
0

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

Sam
  • 111
  • 1
  • 4