public class Person { public String name; public int age; } Person p = new Person(); Class c = p.getClass(); Field nameField = c.getField("name"); String nameValue = (String) nameField.get(p);
import java.lang.reflect.Field; public class ReflectionDemo { public static void main(String[] args) throws Exception { Class cls = Class.forName("java.lang.String"); Field[] fields = cls.getFields(); for (Field field : fields) { System.out.println(field.getName()); } } }In this example, we use the `getField` method to retrieve all public fields of the `String` class. We use the `getFields` method instead of `getField` to retrieve an array of all public fields. We then loop over the array and print the name of each field. Package library: `java.lang.reflect`