public class Person { public String name; public int age; } public class Main { public static void main(String[] args) { Field[] fields = Person.class.getFields(); for (Field field : fields) { System.out.println(field.getName()); } } }
package com.example; public class User { public String username; public String email; } public class Main { public static void main(String[] args) { Field[] fields = User.class.getFields(); for (Field field : fields) { System.out.println(field.getName()); } } }This example is similar to the previous one, but we've added a package declaration at the beginning of the code. The User class has two public fields, "username" and "email". In the Main class, we call getFields() on the User class to retrieve its public fields and print their names. Since we've declared the package as "com.example", this code is part of the "com.example" library.