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?

5
  • 4
    Why do you need multiple methods? Commented Mar 11, 2013 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 Commented Mar 11, 2013 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, "") Commented Mar 11, 2013 at 11:56
  • 4
    I'm sure it's a XY problem, 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.. Commented Mar 11, 2013 at 11:56
  • What you really want is label.setName(i, "") or labels[i].setName(""). :P Commented Mar 11, 2013 at 11:57

2 Answers 2

0

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

Sign up to request clarification or add additional context in comments.

1 Comment

@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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.