lundi 11 janvier 2021

How to get field values of anonymous object in java [closed]

Object = {id: 1, name: "xyz"}

Map<String, Object> map = new HashMap<String, Object>();

Map.Entry<String, Object> entry = map.entrySet().iterator().next();

Object object = entry.getValue();

  1. Class<?> clazz = object.getClass(); try{ Field field = clazz.getField("id"); Object fieldValue = field.get(x); }catch(Exception e){} // throws NoSuchFieldException

  2. Class<?> clz = object.getClass(); try { Field field[] = clz.getDeclaredFields(); field[0].setAccessible(true); System.out.println("Fields: "+field[0].getName()+" : "+field[0].get(object)); }catch(Exception e){}

O/P: Fields: serialVersionUID : 362498820763181265

  1. try { Field f = clz.getField("id") } catch ( NoSuchFieldException ex) { // field doesn't exist } catch (SecurityException ex) { // no access to field } //throws NoSuchFieldException




Aucun commentaire:

Enregistrer un commentaire