当前位置:网站首页>Operations on annotation and reflection
Operations on annotation and reflection
2022-06-11 03:04:00 【Maple Leaf sprite s】
annotation
It can be read by other programs
Built-in annotations
(1)@Override: Represents a method declaration overriding a superclass
(2)@Deprecated: It means that it is dangerous or there is a better choice
(3)@SuppressWarnings: Suppress compile time warnings , Need a parameter
SuppressWarnings(“all”);
SuppressWarnings(“unchecked”);
SuppressWarnings(“unchecked”,“deprecation”);
wait
Yuan notes
Responsible for annotation and other annotations
java.lang.annotation In bag
@Target: Describe the use of annotations
- ElementType.TYPE Class name
- ElementType.FIELD Field
- ElementType.METHOD Method
- wait
@Retention: Describe the lifecycle of annotations
- SOURCE<CLASS<RUNTIME
@Documented: Indicate that the annotation will be included in javadoc in
@Inherited: Indicates that the subclass can inherit the annotation in the parent class
@Target(value = {
ElementType.METHOD}) // Place annotations on Methods
@Retention(value = RetentionPolicy.RUNTIME) // Indicates that the annotation is valid at run time
@Documented // Indicates that the annotation will be generated in javadoc in
@Inherited // Subclasses can inherit the parent class annotation
public @interface Myannotation{
}
Custom annotation
// Yuan notes
public @interface Annotation name {
// Annotation parameters
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
// Custom annotation
public class Test02 {
// Annotations can show assignments
@MyAnnotation2(name = "A")
public void test(){
}
@Myannotation3("") // Parameter is value And there is only one , Then you can omit value
public void test2(){
}
}
@Target({
ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
// Annotated parameters : Parameter type Parameter name ()
String name() default ""; // The default is empty.
int age() default 0;
int id() default -1; // The default value is -1 nonexistence
int[] array() default {
1,2,1};
}
@Target({
ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface Myannotation3{
String value();
}
Reflection
Dynamic language : You can change your structure at run time
(1) Reflection is java Seen as the key to dynamic language , The reflection mechanism allows programs to use reflection during execution Reflection API Get internal information about any class , And directly operate the internal properties and methods of any object
Class c=Class.forName("java.lang.String")
(2) After loading the class , In the method area of heap memory, a Class Object of type ( There is only one class Class object ), This contains the complete class structure information . We can see the structure of the class through this object . This object is like a mirror , Look through this mirror to see the structure of the class , therefore , We call it reflection
Normal mode : Lead-in required “ Package class name –> adopt new Instantiation –> Get the instance object
Ways and means : Instantiate objects –>getClass() Method –> Get complete " Package class " name
Class class
stay Object Class defines the following methods , This method will be inherited by all subclasses
public final Class getClass()
(1)Class It's also a class
(2)Class Objects can only be created by the system
(3) A loaded class is in JVM There will only be one Class example
(4) One Class Object corresponds to a load into JVM One of the .class file
(5) Every instance of a class remembers who it is by Class Instance generated
(6) adopt Class You can get all the loaded structures in a class completely
(7)Class Class is Reflection The root of , For anything you want to load dynamically 、 Operation of class , You have to get Class object
| Method name | Functional specifications |
|---|---|
| static ClassforName(String name) | Returns the specified class name name Of Class object |
| Object newInstance() obsolete | Call parameterless constructor , return Class An instance of an object |
| getName() | Back here Class The name of the entity represented by the object lock |
| Class getSuperClass() | Returns the current Class Object's parent Class object |
| Class[] getinterfaces() | Get current Class Object's interface |
| ClassLoader getClassLoader() | Returns the class loader of this class |
| Constructor[] getConstructors() | Return a Constructor An array of objects |
| Method getMothed(String name,Class…T) | Return to one Method object , The formal parameter type of this object is paramType |
| Field[] getDeclareFields() | return Field An array of objects |
obtain class example
Get from a known class
Class c2=Person.class;Through the instance object of a known class getClass() Method to get
Class c1 = person.getClass();adopt Class Class static methods forName() obtain
Class c3=Class.forName("reflection.Person");The wrapper classes of basic built-in types all have type attribute
Class c4=Integer.TYPE;
Which classes can have class object
(1)class: External class , Member inner class , Static inner class , Local inner classes , Anonymous inner class
(2)interface
(3) Array
(4)enum
(5)annotation: annotation @interface
(6)primitive type: Basic data type
(7)void
import java.lang.annotation.ElementType;
// All types of class
public class test03 {
public static void main(String[] args) {
Class c1=Object.class; // class
Class c2=Comparable.class; // Interface
Class c3=int[].class; // One dimensional array
Class c4=Override.class; // annotation
Class c5= ElementType.class; // enumeration
Class c6=int[][].class; // Two dimensional array
Class c7=Integer.class; // Basic data type
Class c8=void.class; //void
Class c9=Class.class; //Class
System.out.println(c1);
System.out.println(c2);
System.out.println(c3);
System.out.println(c4);
System.out.println(c5);
System.out.println(c6);
System.out.println(c7);
System.out.println(c8);
System.out.println(c9);
// One class ( type ) only one class object
int[] a=new int[10];
int[] b=new int[100];
System.out.println(a.getClass().hashCode());
System.out.println(b.getClass().hashCode());
test03 t1=new test03();
test03 t2=new test03();
System.out.println(t1.getClass().hashCode());
System.out.println(t2.getClass().hashCode());
}
}
Class load memory analysis

Class initialization

Class loader

public class test06 {
public static void main(String[] args) throws ClassNotFoundException {
// Get system classloader
ClassLoader systemClassLoader=ClassLoader.getSystemClassLoader();
System.out.println(systemClassLoader);
// Get the system classloader's parent classloader --> Extend the classloader
ClassLoader parent=systemClassLoader.getParent();
System.out.println(parent);
// Get the parent loader of the extension class loader --> Root loader java Can't get... Directly
ClassLoader grandparent=parent.getParent();
System.out.println(grandparent);
// Test which loader is loading the current class
ClassLoader classLoader = Class.forName("reflection.test06").getClassLoader();
System.out.println(classLoader);
// test jdk Which loader loads the built-in class
classLoader = Class.forName("java.lang.Object").getClassLoader();
System.out.println(classLoader);
// How to get the path that the system class loader can load
System.out.println(System.getProperty("java.class.path"));
}
}
Create an object of a runtime class
Get the complete structure of the runtime class
Get the complete structure of the runtime class by reflection
Field、Method、Constructor、Superclass、Interface、Annotation
class User{
private String name;
private int id;
private int age;
public User(String name, int id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
public User(){
}
@Override
public String toString() {
return ("name="+this.name+",id="+this.id+",age="+this.age);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
// Get class information
public class test07 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
//(1)
Class c1 = Class.forName("reflection.User");
// Get the name of the class Package name . Class name
System.out.println(c1.getName());
// Class obtained simple name Class name
System.out.println(c1.getSimpleName());
//(2)
User user = new User();
c1 = user.getClass();
// Get the name of the class Package name . Class name
System.out.println(c1.getName());
// Class obtained simple name Class name
System.out.println(c1.getSimpleName());
System.out.println("------------------------------");
// Get the properties of the class
Field[] fields = c1.getFields(); // We can only find public attribute
for (Field field : fields) {
System.out.println(field);
}
System.out.println("------------------------------");
fields=c1.getDeclaredFields(); // You can find all the properties
for (Field field : fields) {
System.out.println(field);
}
System.out.println("------------------------------");
// Get specified properties
// Field name=c1.getField("name"); // Make a mistake , because name No public
Field name=c1.getDeclaredField("name");
System.out.println(name);
System.out.println("------------------------------");
// The way to get the class
Method[] methods = c1.getMethods(); // Get all of this class and its parent class public Method
for (Method method:methods){
System.out.println(method);
}
System.out.println("");
methods = c1.getDeclaredMethods(); // Get all the methods of this class
for (Method method:methods){
System.out.println(method);
}
System.out.println("------------------------------");
// Get the specified method
// because java There are heavy loads
Method getName = c1.getMethod("getName",null); // Method name Parameters
System.out.println(getName);
Method setName = c1.getMethod("setName", String.class); // Method name Parameter type .class
System.out.println(setName);
System.out.println("------------------------------");
// Get the specified constructor
Constructor[] constructors = c1.getConstructors();
for (Constructor constructor:constructors){
System.out.println(constructor);
}
System.out.println("");
constructors = c1.getDeclaredConstructors();
for (Constructor constructor:constructors){
System.out.println(constructor);
}
// Get the specified constructor
System.out.println(c1.getDeclaredConstructor(String.class, int.class, int.class));
}
}
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
// Create objects dynamically by reflection
public class test08 {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException, NoSuchFieldException {
//1. get class object
Class c1=Class.forName("reflection.User");
Constructor[] constructors = c1.getConstructors();
//2. adopt class Objects create objects
User user1 =(User) c1.newInstance(); // Call parameterless construction
System.out.println(user1);
System.out.println("---------------------------------------");
// The object is created by the constructor
User user2 =(User) c1.getDeclaredConstructor(String.class,int.class,int.class).newInstance("A",18,18);
System.out.println(user2);
//3. Call normal methods through reflection
User user3 =(User) c1.getDeclaredConstructor().newInstance();
//(1) Access method
Method setAge = c1.getDeclaredMethod("setAge", int.class);
//invoke( Object name , Parameters );
setAge.invoke(user3,1);
System.out.println(user3.getAge());
// user3.setName("1");
// System.out.println(user3.getName());
//4. Manipulate objects through reflection
User user4 =(User) c1.getDeclaredConstructor().newInstance();
Field name = c1.getDeclaredField("name");
// Uncheck the private property Turn off security monitoring of attributes It is several times faster than the reflection direct call
name.setAccessible(true);
name.set(user4,"AA");
System.out.println(user4.getName());
// System.out.println(name.getName());
}
}
Reflection operation generics

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
// Get generics by reflection
public class test09 {
public void test01(Map<String,User> map, List<User> list){
}
public Map<String,User> test02(){
System.out.println("test02");
return null;
}
public static void main(String[] args) throws NoSuchMethodException {
// Get generics through annotations
Method method = test09.class.getMethod("test01", Map.class, List.class);
//get Generic Parameter Types Get generic parameter types
Type[] genericParameterTypes = method.getGenericParameterTypes();
for (Type genericParameterType : genericParameterTypes) {
// Print generic parameter types
System.out.println("#"+genericParameterType);
// Determine whether the generic parameter type is equal to the structured parameter type
if (genericParameterType instanceof ParameterizedType){
Type[] actualTypeArguments = ((ParameterizedType) genericParameterType).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println(actualTypeArgument);
}
}
}
Method method1 = test09.class.getMethod("test02");
Type genericReturnType = method1.getGenericReturnType();
if (genericReturnType instanceof ParameterizedType){
Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println("2 "+actualTypeArgument);
}
}
}
}
Reflection operation comment
getAnnotation
getAnnotations
ORM:Object relationship Mapping Object relation mapping
import java.lang.annotation.*;
import java.lang.reflect.Field;
// Reflection operation comment
public class test10 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class c1 = Class.forName("reflection.B");
// Get annotations by reflection
Annotation[] annotations = c1.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
// Get annotations value Value
Table table =(Table) c1.getAnnotation(Table.class);
System.out.println(table.value());
// Get the annotation specified by the class
Field name = c1.getDeclaredField("name");
Field_ annotation = name.getAnnotation(Field_.class);
System.out.println(annotation.columnName());
System.out.println(annotation.type());
System.out.println(annotation.length());
}
}
@Table("db_B")
class B{
@Field_(columnName = "id",type = "int",length = 10)
private int id;
@Field_(columnName = "age",type = "int",length = 10)
private int age;
@Field_(columnName = "name",type = "varchar",length = 20)
private String name;
public B(int id, int age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
public B() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
// Annotation of class name
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Table{
String value();
}
// Comment for attribute
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Field_{
String columnName();
String type();
int length();
}
边栏推荐
- Problems with JDBC tool classes
- Arduino uses nRF24L01 module for wireless communication
- 巴歇尔槽流量计远程采集物联网关在明渠流量监测的应用
- B_QuRT_User_Guide(16)
- 出栈序列是否是入栈序列
- Win10 安装Office 2016出现错误代码30204-44怎么处理?
- Construction of Flink development environment and wordcount
- Determine whether a string of numbers is the result of a quick sort
- Error in Solr access: error initializing queryelevationcomponent
- List filtering, sorting, verification and other processing methods
猜你喜欢

ASLR

CPT 102_ LEC 16

postgresql源码学习(二十)—— 故障恢复①-事务日志格式

文件合成器

6 best WordPress Image optimizer plug-ins to improve WordPress website performance

蓝桥杯_小蓝吃糖果_鸽巢原理 / 抽屉原理

JS memory leak

Unity项目优化详解(持续补充ing)

Blue Bridge Cup_ Xiao Lan eats candy_ Pigeon nest principle / drawer principle

Niuke: two numbers that only appear once in the array
随机推荐
WordPress article directory plug-in luckywp table of contents setup tutorial
重磅直播!ORB-SLAM3系列之特征匹配(MLPnP、词袋模型等)。
B_ QuRT_ User_ Guide(19)
com. mchange. v2.c3p0. Combopooleddatasource red
Application of the remote acquisition IOT gateway of the Bashir trough flowmeter in open channel flow monitoring
近期学习和更新计划
CPT 102_ LEC 17
Graphacademy course explanation: Fundamentals of neo4j graph data science
蓝桥杯_小蓝吃糖果_鸽巢原理 / 抽屉原理
PIP installation Qt5.
Array full permutation
Niuke: two numbers that only appear once in the array
同一个用户的两次请求SessionId竟然不一致-----记录问题
Forest v1.5.22 release! Kotlin support
sonarqube平台基础使用
深入解析问号表达式
出栈序列是否是入栈序列
File file = new File(“test.txt“)文件路径
Wechat template message errCode ": 40165," errmsg ":" invalid web pagepath
Longest increasing subsequence