[Java] Annotation

Annotation

@Override

public class Person {
  private String firstName;
  private String lastName;

  public Person(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  @Override
  public String toString() {
    return String.format("Name is,%s %s.",
        this.lastName, this.firstName);
  }

  public String getLastName() {
    return this.lastName;
  }

  public String getFirstName() {
    return this.firstName;
  }
}

@WebServlet

Annotation points

Standard annotation

@Deprecated

Integer.java


/**
 *Omission
 * @deprecated
 * It is rarely appropriate to use this constructor. The static factory
 * {@link #valueOf(int)} is generally a better choice, as it is
 * likely to yield significantly better space and time performance.
 */

@Deprecated(since="9")
public Integer(int value) {
    this.value = value;
}

@SuppressWarnings

public class AnnotationBasic {

  public static Integer process() {
   @SuppressWarnings("deprecation")
    var i = new Integer(108);
   return i;
  }

  public static void main(String[] args) {
    System.out.println(process());
  }
}

@SafeVarargs

Self-made annotation

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

//Configuration information declaration
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
//@Annotation definition with interface instruction
public @interface ClassInfo {
  //Declare attributes that can be used in annotations
  String value() default "";
  String version() default "";
  String description() default "";
}

Use annotations in reflection

package mypackage;

//ClassInfo annotation specification
@ClassInfo(version = "2.1", description = "Annotation operation test")
// @ClassInfo("2.1")
public class AnnotationClient {
  public static void main(String[] args) throws ClassNotFoundException {
    //Get subordinate members via Class object
    var clazz = Class.forName("mypackage.AnnotationClient");
    //Get annotation given to class by getAnnotation method
    var info = (ClassInfo)
 clazz.getAnnotation(ClassInfo.class);
    System.out.println("version:" +
        (info.value().equals("") ? info.version() : info.value()));
    System.out.println("Explanation:" + info.description());
  }
}

Reflection method

Object creation

import java.io.File;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;

public class ReflectInstance {

  public static void main(String[] args) {
    try {
      //Get File class
      var clazz = File.class;

      //File object creation via constructor
      var c = clazz.getConstructor(String.class);
      var fl = c.newInstance("./data/data.txt");
      System.out.println(fl);

      //Size 2 array generation
      var list = (File[]) Array.newInstance(File.class, 2);
      Array.set(list, 0, fl);
      System.out.println(Arrays.toString(list));
    } catch (InstantiationException | IllegalAccessException |
        IllegalArgumentException | InvocationTargetException
        | NoSuchMethodException | SecurityException e) {
      e.printStackTrace();
    }
  }
}

Get all methods

import java.io.File;

public class ReflectMethods {

  public static void main(String[] args) {
    //Get File class
    var str = File.class;
    //List method names with getName for public methods under File class
    for (var m : str.getMethods()) {
      System.out.println(m.getName());
    }
  }
}

Method execution

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectInvoke {

  public static void main(String[] args) {
    try {
      //Get File class
      var clazz = File.class;
      //File object creation
      var f1 = clazz.getConstructor(String.class).newInstance("./data/data.txt");
      var f2 = clazz.getConstructor(String.class).newInstance("./data/sample.txt");
      //get and execute renameTo method
      Method m = clazz.getMethod("renameTo", File.class);
      System.out.println(m.invoke(f1, f2));
    } catch (NoSuchMethodException | SecurityException |
        InstantiationException | IllegalAccessException
        | IllegalArgumentException | InvocationTargetException e) {
      e.printStackTrace();
    }
  }
}

Field acquisition, setting

//Get lastName field of Person class

import java.lang.reflect.InvocationTargetException;
import example.Person;

public class ReflectField {

  public static void main(String[] args) {
    try {
      var clazz = Person.class;
      var con = clazz.getConstructor(String.class, String.class);
      var p = con.newInstance("Taro", "Yamada");
      //Field acquisition
      var last = clazz.getDeclaredField("lastName");
      //Explicitly allow access to private fields
      last.setAccessible(true);
      //get/Get field value with set method/Configuration
      last.set(p, "Suzuki");
      System.out.println(last.get(p)); //Suzuki
    } catch (NoSuchMethodException | SecurityException |
        InstantiationException | IllegalAccessException
        | IllegalArgumentException | InvocationTargetException |
        NoSuchFieldException e) {
      e.printStackTrace();
    }
  }
}

package example;
public class Person {
  private String firstName;
  private String lastName;
  public Person(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  @Override
  public String toString() {
    return String.format("Name is,%s %s.",
        this.lastName, this.firstName);
  }
  public String getLastName() {
    return this.lastName;
  }
  public String getFirstName() {
    return this.firstName;
  }
}

Recommended Posts

[Java] Annotation
[Java] Annotation
History of Java annotation
Java
Java
[Java] Creation of original annotation
Java learning (0)
[Java] array
Java protected
[Java] Module
Java array
Studying Java ―― 9
Java scratch scratch
Java tips, tips
Java methods
Java method
java (constructor)
Java array
[Java] ArrayDeque
java (override)
java (method)
Java Day 2018
Java string
java (array)
Java static
Java serialization
java beginner 4
JAVA paid
Studying Java ―― 4
Java (set)
java shellsort
[Java] compareTo
Studying Java -5
java reflexes
java (interface)
Java memorandum
☾ Java / Collection
Java array
Studying Java ―― 1
[Java] Array
[Java] Polymorphism
Read CSV in Java (Super CSV Annotation)
Studying Java # 0
Java review
java framework
Java features
[Java] Inheritance
FastScanner Java
Java features
java beginner 3
Java memo
java (encapsulation)
Java inheritance
[Java] Overload
Java basics
Decompile Java
java notes
java beginner
Java (add2)
JAVA (Map)
[java] interface