-2

Is there an array that I can reference the fields of an object from? The objects fields are of type String, String, String and int. Is it possible to reference these through an array?

atxe
  • 4,825
  • 2
  • 33
  • 48
John
  • 67
  • 4
  • start with a java tutorial on arrays http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html – Chris K Sep 27 '14 at 08:10
  • possible duplicate of [How to declare an array in Java?](http://stackoverflow.com/questions/1200621/how-to-declare-an-array-in-java) – Chris K Sep 27 '14 at 08:11
  • If the objects/values were put *into* an array manually (that is, there is no idiomatic way in Java to "enumerate properties" and reflection is likely not appropriate). However, given the inclusion of the `int` value I expect this is *not* what is actually desired (the best-fitting array would also be `Object[]` after wrapping the integer) - sequences, like arrays, work best with *homogeneous* data. Explaining the *actual* goal/problem and showing *actual* code will likely lead to more useful responses (as most of the answers don't seem to apply). – user2864740 Sep 27 '14 at 08:24

4 Answers4

1

Do you mean that you have something like this?

public class SomeThing
{
    public String thing = "something";
    public String thing2 = "somethingElse";
    public String thing3 = "anotherThing";
    public int id = 42;
}

And you want to access those as an array?

If so, you can do this reflectively, like so:

SomeThing instance = new SomeThing();
Field[] fields = instance.getClass().getFields();
Object[] array = new Object[fields.length]
for(int i = 0; i < fields.length; i++)
{
    fields[i].setAccessible(true);
    array[i] = fields[i].get(instance);
}
KoA
  • 299
  • 2
  • 8
  • 1
    +1 because it appears to be the only answer written after actually reading the question and formulating a reasonable hypothesis from the request, as vague as it is.. however, at this level of understanding reflection is mostly likely not the "correct" approach to use. – user2864740 Sep 27 '14 at 08:25
0

You can reference an object in an array with the [] operator. From there on, it's just a normal reference. E.g.:

myObjectArray[4].getSomePropertyOfMyObject();
Mureinik
  • 252,575
  • 45
  • 248
  • 283
0

What do you mean? Can you explain it better. You can have an Array of objects in Java.

If for example your object is called Animal you can create an array of Animals like this:

Animal[] animals= new Animal[sizeOfAnimals];

Is it what you want? Just substitute Animal with your object.

Alboz
  • 1,995
  • 18
  • 24
0
 Cat [] list = new Cat[10];

So once you have a list and objects of a type inside the list then you can call them like you would any other object.

 list[0].methodName();

Notice list[0] behaves like a Cat object, because that is what it holds.

apxcode
  • 7,367
  • 7
  • 25
  • 39