进阶day12-自定义注解
This commit is contained in:
25
javaSE-day12/src/com/inmind/annotation03/MyAnnotation.java
Normal file
25
javaSE-day12/src/com/inmind/annotation03/MyAnnotation.java
Normal file
@@ -0,0 +1,25 @@
|
||||
package com.inmind.annotation03;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
/*
|
||||
自定义注解
|
||||
1.注解的关键字:@interface
|
||||
2.注解中可以定义属性
|
||||
定义属性的格式:数据类型 属性名();
|
||||
设置默认值的属性的格式:数据类型 属性名() default 属性值;
|
||||
3.注解的属性的类型有限制
|
||||
八大基本数据类型,String Class 注解 枚举
|
||||
以上类型的一维数组
|
||||
4.注解中有一个特殊的属性名 value
|
||||
当属性赋值时,如果只有一个value属性在赋值,那么value = 省略!!!
|
||||
|
||||
5.注解如何使用:它可以修饰类,构造器,属性,方法,注解,参数
|
||||
|
||||
6.注解在使用时,属性值必须赋值,默认值可以覆盖
|
||||
*/
|
||||
public @interface MyAnnotation {
|
||||
public static final int age = 1;//注解中的常量
|
||||
String name() default "张三";//name属性
|
||||
int value();//value属性
|
||||
}
|
||||
40
javaSE-day12/src/com/inmind/annotation03/Student.java
Normal file
40
javaSE-day12/src/com/inmind/annotation03/Student.java
Normal file
@@ -0,0 +1,40 @@
|
||||
package com.inmind.annotation03;
|
||||
|
||||
@MyAnnotation(name = "李四",value = 1)
|
||||
public class Student {
|
||||
//属性(成员变量)
|
||||
@MyAnnotation(name = "王五",value = 2)
|
||||
String name;
|
||||
int age;
|
||||
|
||||
//无参构造方法
|
||||
@MyAnnotation(value = 1)
|
||||
public Student() {
|
||||
}
|
||||
|
||||
//满参构造方法
|
||||
private Student(String name, int age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
//行为(成员方法)
|
||||
@MyAnnotation(1)
|
||||
public void show(){
|
||||
System.out.println("无参无返回值的show方法执行了");
|
||||
}
|
||||
|
||||
@MyAnnotation(1)
|
||||
private int show(@MyAnnotation(1) int i){
|
||||
System.out.println("有参有返回值的show方法执行了");
|
||||
return i+100;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Student{" +
|
||||
"name='" + name + '\'' +
|
||||
", age=" + age +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user