java get attributes from class

java get attributes from class

To get the attributes (fields) of a class in Java, you can use the getDeclaredFields() method of the Class class. This method returns an array of Field objects that represent the fields of the class.

Here's an example of how to use the getDeclaredFields() method to get the attributes of a class:

import java.lang.reflect.Field;

public class Main {
  public static void main(String[] args) throws Exception {
    Class cls = Class.forName("java.util.Date");

    Field[] fields = cls.getDeclaredFields();
    for (Field field : fields) {
      System.out.println(field.getName());
    }
  }
}
S‮ecruo‬:www.lautturi.com

This code uses the forName() method of the Class class to get the Class object for the java.util.Date class. The getDeclaredFields() method is then called on the Class object to get an array of Field objects that represent the fields of the Date class. The Field objects are then iterated using a for-each loop to print the names of the fields.

You can also use the getFields() method of the Class class to get the public fields of the class, or the getDeclaredField() or getField() methods to get a specific field by name.

Created Time:2017-11-03 22:21:08  Author:lautturi