0

I have a collection of records whose variables I want to assign to a set of labels in a UI. The problem is that I have to write duplicate code for each record to be displayed, such as:

label.setName1("")
label.setDate1("")

label.setName2("")
label.setDate2("")

Is there a way to increment the number in the method, which is the position of the record in the collection through a loop or something so I don't have to have duplicate code in my class?

Sam R.
  • 16,027
  • 12
  • 69
  • 122
ojap
  • 126
  • 1
  • 2
  • 11
  • 4
    Why do you need multiple methods? –  Mar 11 '13 at 11:55
  • for such a scenerio we use a list. But your question looks unclear as the problem could be tackled in other ways; if we can get to know what you are trying to achive – Naveen Babu Mar 11 '13 at 11:55
  • 1
    You could use reflection, however it would be much better to change your methods to pass the number by parameter e.g. `label.setName(1, "")` – RoToRa Mar 11 '13 at 11:56
  • 4
    I'm sure it's a XY problem, http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem. You need to provide your label class so we can help you find a solution. Otherwise you'll need to use java reflexion for that.. – Majid Laissi Mar 11 '13 at 11:56
  • What you really want is `label.setName(i, "")` or `labels[i].setName("")`. :P – cHao Mar 11 '13 at 11:57

2 Answers2

0

You can do this using reflection. You can look here or here for more details.

Community
  • 1
  • 1
pushy
  • 9,535
  • 5
  • 26
  • 45
  • @ojap Don't use reflection just because you think it's right. In most cases reflection is the wrong tool, because it's slow and not the "Java way" to do things. We can help you find a better and easier way, if you tell use what you are doing. – RoToRa Mar 12 '13 at 16:02
0

yes, use java reflection. You can get the methods of a class with some names and then make them work for you.

MyClass.getMethods()  

will return all methods of your class. And inherited methods too. If you want only methods declared in your class you can use getDeclaredMethods() instead (read this)

These will return an array of objects with Type Method. After that you can invoke them for your object.

But I think it will be better to change your class structure and keep arrays of names, labels and other things instead of single properties for each one.

shift66
  • 11,760
  • 13
  • 50
  • 83