3

I was wondering how to get KEY and VALUE from object in JAVA

my object is like below

Object obj = [{ index_a = 1, index_b = 2}, { index_a = 3, index_b = 4}]

I want to get index_a, 1, index_b, 2, ...

Jay
  • 45
  • 1
  • 7

2 Answers2

1

I'm guessing you've come to Java from a language in which objects have loose types and are accessed approximately as key, value pairs which are often defined at run time. An example is json converting directly to JS objects with minimal translation.

That does not describe Java at all. The type and structure of Java objects are explicitly defined at compile time and expected to be accessed through methods available at compile time. For an experienced Java coder, your question is confusing because accessing object variables as keys and values is just not how things are generally done in Java.

If your object is going to store a list of maps from string keys to date values (for example), then that would normally be expressed in java as a variable of type List<Map<String,Date>>.

sprinter
  • 27,148
  • 6
  • 47
  • 78
0

I know this is kind of an old question, but for those who actually want an answer to guide them in the (more or less) right direction, you can do something along the lines of below to get an object's fields/values:

import java.lang.reflect.Field;

public String getObjectFields(obj) {
    // See:
    //  - https://stackoverflow.com/questions/13400075/reflection-generic-get-field-value
    //  - https://www.geeksforgeeks.org/reflection-in-java
    //  - https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getDeclaredField-java.lang.String-
    Class<?> objClass = obj.getClass();
    Field[] objFields = objClass.getDeclaredFields();

    Map<String, String> entriesMap = new HashMap<>();

    for (Field field : objFields) {
        String fieldSuffix = field.toString().replaceAll("(^.*)(\\.)([^\\.]+)\$", "\$3");

        field.setAccessible(true);
        entriesMap.put(fieldSuffix, field.get(obj));
    }

    return entriesMap;
}
yuyu5
  • 365
  • 4
  • 11
  • sry too late to see your answer. i solved the problem, but your answer is helpful. thanks – Jay Nov 16 '22 at 05:43