注解(Annotation)
框架的底层!
1. 什么是注解
Annotation的作用:
- 不是程序本身,可以对程序做出解释;
- 可以被其他程序读取。
//什么是注解
public class Test01 extends Object{
@Override
public String toString() {
return super.toString();
}
}
可以通过反射机制编程实现对这些元数据的访问;
2. 内置注解
@Override
public String toString() {
return super.toString();
}
@Deprecated
public static void test01(){
System.out.println("Deprecated");
}
@SuppressWarnings("all")
public static void test02(){
System.out.println("SuppressWarnings");
}
3. 元注解
元注解的作用就是负责注解其他注解;
@Target 描述注解的使用范围
@Retention 表示需要在什么级别保存该注释信息
@Documented 该注解将被包含在javadoc中
@Inherited 说明子类可以继承父类中的该注解
//测试元注解
@MyAnnotation1
public class Test02 {
@MyAnnotation1
public void test(){
}
}
//定义一个注解@MyAnnotation1
//Target表示可以注解在什么地方
@Target(value = {ElementType.METHOD,ElementType.TYPE})
//Retention表示我们的注解在什么地方有效
@Retention(value = RetentionPolicy.RUNTIME)
//Documented表示是否将我们的注解生成在javadoc中
@Documented
//Inherited子类可以继承父类的注解
@Inherited
@interface MyAnnotation1{
}
//自定义注解
public class Test03 {
@MyAnnoatation2(name = "zhangsan",age = 18)
public void test(){
}
@MyAnnoatation3("zhangsan")
public void test3(){
}
}
//定义的注解可以使用在类和方法上,在运行时有效
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnoatation2{
//注解的参数:参数类型+参数名();
String name() default ""; //设置默认值为空
int age() default 0; //设置默认值为0
int id() default -1; //如果默认值为-1,代表不存在
String[] schools() default {"清华","北大"};
}
//只有一个参数的时候,尽量使用value
@Target({ElementType.TYPE,ElementType.METHOD})
@interface MyAnnoatation3{
String value();
}
反射(Reflection)
反射是java被视为动态语言的关键,反射机制允许程序在执行期借助于Reflection API取得任何类的内部信息,并能直接操作任意对象的内部属性及方法。
getClass()方法:返回一个类对象
public final Class getClass()
此方法返回值的类型是一个Class类,此类是java反射的源头,实际上所谓反射从程序的运行结构来看也很好理解,即:可以通过对象反射求出类的名称。
类的主动引用(一定会发生类的初始化)
//通过反射获取类的Class对象
Class c1 = Class.forName("com.zkx.reflection.User");
System.out.println(c1);
System.out.println(c1.hashCode());
Class类的创建方式:
public class Test02 {
public static void main(String[] args) throws ClassNotFoundException {
Person person = new Student();
System.out.println("这个人是:"+person.name);
//方式一:通过对象获得
Class c1 = person.getClass();
System.out.println(c1.hashCode());
//方式二:forName获得
Class c2 = Class.forName("com.zkx.reflection.Student");
System.out.println(c2.hashCode());
//方式三:通过类名.class获得
Class c3 = Student.class;
System.out.println(c3.hashCode());
//方式四:基本内置类型的包装类都有一个TYPE属性
Class c4= Integer.TYPE;
System.out.println(c4.hashCode());
//获得父类类型
Class c5 = c1.getSuperclass();
System.out.println(c5);
}
}
class Person{
public String name;
public Person(String name) {
this.name = name;
}
public Person() {
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
'}';
}
}
class Student extends Person{
public Student() {
this.name ="学生";
}
}
class Teacher extends Person{
public Teacher() {
this.name ="老师";
}
}
获得系统类的加载器
public class Test06 {
public static void main(String[] args) throws ClassNotFoundException {
//获得系统类的加载器
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
System.out.println(classLoader);
//获取系统类加载器的父类加载器-->扩展类加载器
ClassLoader parent = classLoader.getParent();
System.out.println(parent);
//获取扩展类加载器的父类加载器-->根加载器(c/c++)
ClassLoader parent1 = parent.getParent();
System.out.println(parent1);
//测试当前类是哪个加载器加载的
ClassLoader classLoader1 = Class.forName("com.zkx.reflection.Test06").getClassLoader();
System.out.println(classLoader1);
}
}
public class Test07 {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
//获取Class对象
Class c1 = Class.forName("com.zkx.reflection.User");
//构造一个对象
User user =(User) c1.newInstance();
System.out.println(user);
//通过构造器创建对象
Constructor constructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
User user2 =(User) constructor.newInstance("张三", 001, 18);
System.out.println(user2);
//通过反射调用方法
User user3 = (User)c1.newInstance();
//通过反射获取一个方法
Method setName = c1.getDeclaredMethod("setName", String.class);
setName.invoke(user3,"123");
System.out.println(user3.getName());
//通过反射操作属性
//不能直接操作私有属性,我们需要关闭程序的安全检测,属性或者方法的setAccessible(true)
User user4 = (User)c1.newInstance();
Field name = c1.getDeclaredField("name");
name.setAccessible(true);
name.set(user4,"456");
System.out.println(user4.getName());
}
}
//获得类的信息
public class Test08 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
Class c1 = Class.forName("com.zkx.reflection.User");
//获得类的名字
System.out.println(c1.getName());
System.out.println(c1.getSimpleName());
System.out.println("====================");
//获得类的属性
Field[] fields = c1.getDeclaredFields();
for (Field field : fields) {
System.out.println(field);
}
//获得指定属性的值
System.out.println();
Field name = c1.getDeclaredField("name");
System.out.println(name);
//获得类的方法
System.out.println("====================");
Method[] methods = c1.getMethods();
for (Method method : methods) {
System.out.println(method);
}
System.out.println();
methods = c1.getDeclaredMethods();
for (Method method : methods) {
System.out.println(method);
}
//获得指定方法
System.out.println();
System.out.println();
Method getName = c1.getMethod("getName", null);
Method setName = c1.getMethod("setName", String.class);
System.out.println(getName);
System.out.println(setName);
//获得指定的构造器
System.out.println("====================");
Constructor[] constructors = c1.getConstructors();
for (Constructor constructor : constructors) {
System.out.println(constructor);
}
}
分析性能问题
public class Test09 {
//普通方式调用
public static void test01(){
User user = new User();
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
user.getName();
}
long endTime = System.currentTimeMillis();
System.out.println("普通方式执行10亿次:"+(endTime-startTime)+"ms");
}
//反射方式调用
public static void test02() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
User user = new User();
Class c1 = user.getClass();
Method setName = c1.getDeclaredMethod("setName", String.class);
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
setName.invoke(user,"zhangsan");
}
long endTime = System.currentTimeMillis();
System.out.println("反射方式执行10亿次:"+(endTime-startTime)+"ms");
}
//反射方式调用,关闭检测
public static void test03() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
User user = new User();
Class c1 = user.getClass();
Method getName = c1.getDeclaredMethod("getName", null);
getName.setAccessible(true);
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
getName.invoke(user,null);
}
long endTime = System.currentTimeMillis();
System.out.println("关闭检测方式执行10亿次:"+(endTime-startTime)+"ms");
}
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
test01();
test02();
test03();
}
}
通过反射获取泛型
public class Test10 {
public void test01(Map<String,User> map, List<User> list){
System.out.println("test01");
}
public Map<String,User> test02(){
System.out.println("test02");
return null;
}
public static void main(String[] args) throws NoSuchMethodException {
Method method = Test10.class.getMethod("test01", Map.class, List.class);
Type[] genericParameterTypes = method.getGenericParameterTypes();//获得方法的参数类型
for (Type genericParameterType : genericParameterTypes) {
System.out.println("#"+genericParameterType);
if(genericParameterType instanceof ParameterizedType){
Type[] actualTypeArguments = ((ParameterizedType) genericParameterType).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println(actualTypeArgument);
}
}
}
System.out.println("=====================");
method = Test10.class.getMethod("test02",null);
Type genericReturnType = method.getGenericReturnType();
if(genericReturnType instanceof ParameterizedType){
Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println(actualTypeArgument);
}
}
}
}
反射操作注解
public class Test11 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class c1 = Class.forName("com.zkx.reflection.Student2");
//通过反射获得注解
Annotation[] annotations = c1.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
//获得注解value的值
Tablek tablek =(Tablek) c1.getAnnotation(Tablek.class);
String value = tablek.value();
System.out.println(value);
//获得类指定的注解
Field f = c1.getDeclaredField("name");
Fielda annotation = f.getAnnotation(Fielda.class);
System.out.println(annotation.columName());
System.out.println(annotation.type());
System.out.println(annotation.length());
}
}
@Tablek("db_student")
class Student2{
@Fielda(columName = "db_id",type = "int",length = 10)
private int id;
@Fielda(columName = "db_age",type = "int",length = 10)
private int age;
@Fielda(columName = "db_name",type = "int",length = 3)
private String name;
public Student2() {
}
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;
}
public Student2(int id, int age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
@Override
public String toString() {
return "Student2{" +
"id=" + id +
", age=" + age +
", name='" + name + '\'' +
'}';
}
}
//类名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Tablek{
String value();
}
//属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Fielda{
String columName();
String type();
int length();
}