当前位置:网站首页>Notes and notes
Notes and notes
2022-07-04 05:54:00 【Chang'an has a hometown y】
java Notes and notes for
1 notes
Classification of notes
Single-line comments : //
Multiline comment : /* */
Documentation Comments :/** */
effect : Deliver additional information , Show the programmer , Not involved in compilation
2 notes
Annotation It is a special mark in the code , You can compile 、 Class loading 、 Read while running
, And carry out the corresponding treatment .
2.1 The difference between annotation and annotation

2.2 Custom annotation
package com.yq.day72;
public @interface MyAnno {
// Range of attribute types Basic data types string class Enumeration type Annotation type
// And arrays of the above types
int age();
double price();
String name();
String[] names();
Class c();
MyAnno3 anno();
// Annotations cannot inherit
}
@interface MyAnno3 {
}
Annotations cannot be inherited
2.3 Use of annotations
Instantiate the object not through new, It is Property name = Property value
Use When Assign values to each attribute
@ Annotation name ( Property name 1=value, Property name 2=value,....)
Be careful :
1. Each attribute must be assigned
2. There are default values that can be omitted
3. There's only one property , And for value, The assignment can be simplified
4. Copy and use of arrays {}
5. The value of a reference type cannot be null
2.4 Annotation processor
Combine reflection to apply
Specific steps to use
1. Get registered information through reflection
2. Get file bytecode object
3. How to get objects , Determine whether the above method uses annotations
4. An example of getting annotations is used
5. Get attribute value , To operate
Method used : Belong to category Class
| boolean isAnnotation() | If so Class Object represents an annotation type, and returns true. |
|---|---|
| A getAnnotation(Class annotationClass) | If there is a comment of the specified type for the element , Then return these comments , Otherwise return to null. |
Code instance :
package com.yq.day72;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
/** * @author [email protected] * @description * @since 2022/07/02 11:41 * Create a learning object , Don't use new The way , Use reflection and annotation to realize * name The length of is 5 Between , Age 18-25 Between */
// Test class
public class Demo04 {
// Define a bytecode file object , Assign a value
static Class<?> aClass;
static {
try {
aClass = Class.forName("com.yq.day72.Student");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException, InstantiationException, IllegalAccessException {
Student zhansa = getInstance("zga", 293);
System.out.println(zhansa);
}
public static Student getInstance(String name,int age) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
// Verification of name obtain student Properties of name
Field name1 = aClass.getDeclaredField("name");
// Decide whether to use annotations Judgment properties name Whether there are notes on
boolean a1 = name1.isAnnotationPresent(NameLimit.class);
if (a1){
// Get an instance of the annotation
NameLimit a2 = name1.getAnnotation(NameLimit.class);
// Get the attribute value of the annotation
int length = a2.length();
// Judge
if (name.length()>length){
throw new IllegalArgumentException(" The length is large ");
}
}
// Verification of age obtain age Properties of
Field age1 = aClass.getDeclaredField("age");
// Judge if there is a comment
boolean annotationPresent = age1.isAnnotationPresent(AgeLimit.class);
if (annotationPresent){
// Get an instance of the annotation
AgeLimit annotation = age1.getAnnotation(AgeLimit.class);
// Get attribute value
int i = annotation.maxAge();
int i1 = annotation.minAge();
if (age>i || age <i1){
throw new IllegalArgumentException(" Age is illegal !!!!!");
}
}
// Get construction method
Constructor<?> declaredConstructor = aClass.getDeclaredConstructor(String.class, int.class);
// Ignore restrictions
declaredConstructor.setAccessible(true);
// Create student objects
Student o = (Student) declaredConstructor.newInstance(name, age);
return o;
}
}
class Student{
// annotation
@NameLimit
String name;
// annotation
@AgeLimit
int age;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
private Student(String name, int age) {
this.name = name;
this.age = age;
}
}
// Yuan notes
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface NameLimit{
int length() default 5;
}
// Yuan notes
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface AgeLimit{
int maxAge() default 25;
int minAge() default 18;
}
2.5 Yuan notes
Notes describing annotations , Metadata meta data
Common meta notes
**@Retention Yuan notes , To define the retention level of our own annotations .**
- RetentionPolicy.RUNTIME
- RetentionPolicy.CLASS Default
- RetentionPolicy.SOURCE
**@Target Yuan notes , The purpose of annotation **
For annotations , Goals that can work :
1. The whole class ElementType.TYPE
2. Member variables ElementType.FIELD
3. Construction method ElementType.CONSTRUCTOR
4. Member method ElementType.METHOD
2.6 annotation VS The configuration file

边栏推荐
- What is MQ?
- Kubernets first meeting
- lightroom 导入图片灰色/黑色矩形 多显示器
- LC周赛300
- 报错cvc-complex-type.2.4.a: 发现了以元素 ‘base-extension‘ 开头的无效内容。应以 ‘{layoutlib}‘ 之一开头。
- SQL injection - injection based on MSSQL (SQL Server)
- left_and_right_net正常版本
- The difference between PX EM rem
- 1480. Dynamic sum of one-dimensional array
- 剑指 Offer II 038. 每日温度
猜你喜欢

APScheduler如何设置任务不并发(即第一个任务执行完再执行下一个)?

QT 获取随机颜色值设置label背景色 代码

ES6 modularization

buuctf-pwn write-ups (8)

Gridview出现滚动条,组件冲突,如何解决

gslb(global server load balance)技术的一点理解

My NVIDIA developer journey - optimizing graphics card performance

如何展开Collapse 的所有折叠面板

Configure cross compilation tool chain and environment variables
![[openvino+paddle] paddle detection / OCR / SEG export based on paddle2onnx](/img/a9/72791cbcc6c9da45e89450ab2820c1.jpg)
[openvino+paddle] paddle detection / OCR / SEG export based on paddle2onnx
随机推荐
My NVIDIA developer journey - optimizing graphics card performance
JS arguments parameter usage and explanation
Online shrimp music will be closed in January next year. Netizens call No
Grounding relay dd-1/60
The end of the Internet is rural revitalization
js获取对象中嵌套的属性值
一键过滤选择百度网盘文件
HMS v1.0 appointment. PHP editid parameter SQL injection vulnerability (cve-2022-25491)
How to implement lazy loading in El select (with search function)
Zhanrui tankbang | jointly build, cooperate and win-win zhanrui core ecology
What is MQ?
Canoe panel learning video
How to clone objects
VB. Net simple processing pictures, black and white (class library - 7)
VB. Net GIF (making and disassembling - optimizing code, class library - 5)
MySQL的information_schema数据库
Overview of relevant subclasses of beanfactorypostprocessor and beanpostprocessor
如何获取el-tree中所有节点的父节点
Review | categories and mechanisms of action of covid-19 neutralizing antibodies and small molecule drugs
Recommended system 1 --- framework