Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get attributes of an Object in Java?

Tags:

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
like image 904
Majid Laissi Avatar asked Nov 20 '25 01:11

Majid Laissi


1 Answers

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

like image 75
AlexR Avatar answered Nov 21 '25 15:11

AlexR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!