timerring

10 Annotations and Reflection

January 12, 2024 · 1 min read
Tutorial
Java
If you have any questions, feel free to comment below. Click the block can copy the code.
And if you think it's helpful to you, just click on the ads which can support this site. Thanks!

10.1 Annotations #

(1) Annotations, also called metadata, describe packages, methods, fields, constructors, local variables, and other program elements.
(2) Annotations do not affect program logic, but can be processed at compile time or runtime.
(3) In Java SE, annotations serve relatively simple purposes, such as marking obsolete features or suppressing warnings. In Java EE, they play a more important role, such as configuring aspects of an application in place of the verbose code and XML configuration left over from older Java EE versions.

10.1.1 Common Annotations #

(1) @Override: Requires a method to override another method; it applies only to methods. The method name and parameter list must match.
(2) @Overload: Requires a method to overload another method; it applies only to methods. The method name must match, but the parameter lists must differ.
(3) @Deprecated: Indicates that a program element (class or method) is obsolete.
(4) @SuppressWarnings: Suppresses compiler warnings.

10.1.2 Meta-annotations #

An annotation that annotates other annotations is called a meta-annotation.

(1) Retention: Specifies the scope in which an annotation is retained.
(2) Target: Specifies where an annotation can be used.
(3) Document: Specifies whether an annotation appears in Javadoc.
(4) Inherited: Subclasses inherit annotations from their parent class.

10.2 Reflection #

Reflection: Dynamically load classes and access instance methods, fields, and other members.

10.2.1 Common APIs #

(1) java.lang.Class
(2) java.lang.reflect.Method
(3) java.lang.reflect.Field
(4) java.lang.reflect.Constructor

package org.timerring;

public class Calculator {
    public String name;

    public Calculator() {}

    public Calculator(String name) {
        this.name = name;
    }

    public int add(int a, int b) {
        return a + b;
    }
}
package org.timerring;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        Class<?> cls = Class.forName("org.timerring.Calculator");
        Object o = cls.newInstance();
        // Ordinary call: o.add(3, 4)
        // Here, use reflection:
        Method method = cls.getMethod("add", int.class, int.class);
        int res = (int)method.invoke(o, 3, 4);
        System.out.println(res);
        // A member variable is called a field
        Field field = cls.getField("name");
        field.set(o, "My Calculator!");
        System.out.println(field.get(o));

        Constructor<?> constructor = cls.getConstructor(String.class);
        Object new_o = constructor.newInstance("New Calculator!");
        System.out.println(new_o);
        // Compare with the usual approach:
        // Calculator o = new Calculator();
        // System.out.println(o.add(11, 22));
        // o.name = "New Calculator!";
        // System.out.println(o.name);
        // Calculator newObject = new Calculator("New Calculator!");
        // System.out.println(newObject);
    }
}

10.2.2 Advantages and Disadvantages #

Advantage: Objects can be created and used dynamically, offering flexibility.
Disadvantage: Execution is slow.

Related readings


<< prev | 09 Exception... Continue strolling 11... | next >>

If you want to follow my updates, or have a coffee chat with me, feel free to connect with me: