0

I am trying to use reflection to return an int based on a String that's automatically generated:

try {
    ItemWeight myObject = new ItemWeight();
    Method method = ItemWeight.class.getMethod(easyItem.replace(" ", ""));
    weight = (Integer) method.invoke(myObject);

        } catch (Exception e) {
            e.printStackTrace();

        }

However, if the String begins with the number it is throwing an error:

public int 0PtsAllowed()
 {
 return 14;
 }

This returns the following when compiling: Syntax error on token "0", delete this token

Any help would be greatly appreciated.

Thanks, Josh

Josh
  • 2,685
  • 6
  • 33
  • 47
  • `Syntax error on token "0", delete this token` is a compile time error, since you can't name methods like that. If you want, you can append 0 to the end if you really need a number there. Also consider having your method accept [parameters](http://stackoverflow.com/questions/2202381/reflection-how-to-invoke-method-with-parameters) if all you need the number for is similar methods that are unique in name. – A--C Feb 23 '13 at 22:08

1 Answers1

0

I'm suprised that it compiles. 0PtsAllowed is not a legal Java identifier. You certainly won't be able to invoke it.

ptsAllowed0 would do it but that said, I question your design. How about ptsAllowed(int points)

[EDIT] Late at night, I've just noticed that indeed you have a compiler error but the reasoning stands. Time for bed...

Simon
  • 14,407
  • 8
  • 46
  • 61
  • I considered a method accepting a parameter, but there are too many possible string inputs, and would require a huge if/else statement. – Josh Feb 24 '13 at 02:15
  • Why string and why lots of ifs? It's worth describing your need as there is often a simple, elegant solution that you've just overlooked. – Simon Feb 24 '13 at 08:53
  • Basically I am using this solution in two different situations. The first I use it to take a unique string and translate it to another string. In that instance it is translating database column names into user friendly readable strings. The second instance is the one shown above, where I then take those user friendly strings, remove the spaces and then return a number based on which string it is. – Josh Feb 24 '13 at 13:01