Discovering Class Fields

Class c = someObject.getClass();
											Field[] publicFields = c.getFields();
											for (int i = 0; i < publicFields.length; i++) {
											String fieldName = publicFields[i].getName();
											Class fieldType = publicFields[i].getType();
											String fieldTypeStr = fieldType.getName();
											System.out.println("Name: " + fieldName);
											System.out.println("Type: " + fieldTypeStr);
											}

You can discover the public fields that belong to a class by using the getFields() method on a Class object. The getFields() method returns an array of Field objects containing one object per accessible public field. The accessible public fields returned do not all have to be fields contained directly within the class you are working with. The following fields are also returned:

  • Fields ...

Get Java™ Phrasebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.