- Language and JVM feature that gives us Runtime access to information about our application's classes, and objects.
- Those features are available to us through the
java.lang.reflect
(Reflection API) package.
- Returns the runtime class of an object.
- The returned Class object is the object that is locked by static synchronized methods of the represented class.
- class.getDeclaredConstructor()
- Returns all the constructors declared by the class. (public, protected, default (package) access, and private constructors)
- class.getConstructor()
- Returns only the public constructors declared by the class.
- Fields are variables that belong to a class or object.
- class.getDeclaredFields()
- Returns all the fields declared by the class. (public, protected, default (package) access, and private fields)
- Includes inherited fields.
- class.getFields()
- Returns only the public fields declared by the class.
- Includes inherited fields.
- class.getDeclaredField(<field_name>)
- Returns a specific field declared by the class.
- Includes inherited fields.
- Throws NoSuchFieldException if the field does not exist.
- Fields that are generated by the compiler for internal usage.
- For example, the
this
keyword is a synthetic field. - field.isSynthetic()
- Returns true if the field is synthetic.
- field.isEnumConstant()
- Returns true if the field is an enum constant.
- field.setAccessible(true)
- Allows us to access private fields.
- if classes belong to different modules, that don't allow access to those class, we can use
--add-opens
to allow access to private fields.
- Methods are functions that belong to a class or object.
- getMethod() searches in order backwards through the class hierarchy.
- getDeclaredMethods()
- Returns all the methods declared by the class. (public, protected, default (package) access, and private methods)
- Includes inherited methods.
- getMethods()
- Returns only the public methods declared by the class.
- Includes inherited methods.
- getDeclaredMethod(<method_name>, <parameter_types>)
- Returns a specific method declared by the class.
- Looks only at the methods in current class.
- Throws NoSuchMethodException if the method does not exist.
- getMethod(<method_name>, <parameter_types>)
- Returns a specific public method declared by the class.
- Includes inherited methods.
- Throws NoSuchMethodException if the method does not exist.