-1

I have an arraylist of classes. I need to randomly pick 2 classes from the arraylist, then call an attribute from them. How would I do this?

I can't just do

(array_list_name.get(random_number)).attribute_name();

as i'm not calling the attribute of the class, i'm attempting to call the attribute from get, and that obviously won't work.

P.S. I have already initialized all the classes.

  • `array_list_name.get(random_number).attribute_name();` should be ok, without the extra parenthesis in `array_list_name` – elbraulio Dec 15 '18 at 00:32
  • If I do that I get the error "Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method values() is undefined for the type Object" with values() being the attribute im trying to call. – Justin Bancale Dec 15 '18 at 00:37
  • so, you initialize classes, add them to `array_list_name`, you get an element of `array_list_name` using `get(a_number)` and try to get a value from the element and it throws an exception that says the class you have got does nor have the method you called? can you share the way you fill the `array_list_name`? – elbraulio Dec 15 '18 at 01:29
  • How does one **call** an _attribute_? – Zephyr Dec 15 '18 at 04:18

1 Answers1

-1

I think something may be missing from the question. Are you trying to access the attribute's value? If you know the name of the attribute in all objects you have in the list, the following should work:

SomeType obj = list_of_objects[0]
String val = obj.attribute_name

Or are you perhaps trying to dynamically call a method name that is contained in an attribute's value? If so, then (along with the code above) you'll want to look at how to call a method dynamically. The answer to that can be found here: https://stackoverflow.com/a/161005/4700298