Majid Laissi
Majid Laissi

Reputation: 19788

How to get attributes of an Object in Java?

I have a function that returns an Object

The toString() method shows that my object has two BigDecimal attributes. But I don't know how to get them in the code ?

enter image description here

My function uses hibernate to get results from a query is :

public Object executeQuery(final String sql) {
    final Query query = getSessionFactory().getCurrentSession().createSQLQuery(sql);
    return query.list().get(0);
}

Thank you.

-- Additional infos:

obj.getClass().getDeclaredFields(); // empty array []
obj.getClass().getName();           // [Ljava.lang.Object;
final BigDecimal b = (BigDecimal) obj[0]; //Compilation error: The type of the expression must be an array type but it resolved to Object

Upvotes: 2

Views: 2786

Answers (5)

vels4j
vels4j

Reputation: 11298

Get first what class name of that object by

System.out.println(obj.getClass());

Since you are running a sql query, result might be an Entity or Object[].

when you came to know retrieved object from query is an Object[] you can iterate like

if( obj instanceof Object[] ) {
       Object[] objA = (Object[])obj;
       for(Object atomicObj : objA ) {
         System.out.println(atomicObj);
       }
}

It works for all elements which presents in object array. This time you may get BigDecimal, next query might return a String and BigDecimal.

Upvotes: 1

RoflcoptrException
RoflcoptrException

Reputation: 52229

Judging from your comments, your Object is and Object array.

So you should first cast the result to an Object array:

Object[] obj = (Object[]) query.list().get(0);

Then, you should be able to access the first BigDecimal like that:

BigDecimal b = (BigDecimal) obj[0];

Probably, you want to add some exception handling.

Upvotes: 2

gaborsch
gaborsch

Reputation: 15758

UPDATE:

You have a resultset with 2 columns.

Object[] result= query.list().get(0);
BigDecimal number1 = (BigDecimal) result[0];
BigDecimal number2 = (BigDecimal) result[1];

Upvotes: 1

Affe
Affe

Reputation: 47954

It is not an Object, it is an Array of Objects.

BigDecimal firstColumn = (BigDecimal) ((Object[])query.list().get(0))[0];
BigDecimal secondColumn = (BigDecimal) ((Object[])query.list().get(0))[1];

That's all.

Upvotes: 1

AlexR
AlexR

Reputation: 115328

obj.getClass().getDeclaredFields() can help you. Generally learn reflection API. If you object bean you can also use Jackarta BeanUtils.

Upvotes: 4

Related Questions