zoukankan      html  css  js  c++  java
  • 反射与注解

    Q1:静态语言与动态语言

    静态类型语言:编译时确定数据类型

    动态类型语言:运行时确定数据类型

    静态:C#,Java,C,C++

    动态:JavaScript,python,perl,ruby,php

    Q2:反射概要

    1.概念:

    反射就是可以在运行时加载类信息,并可以创建其对象访问其属性和方法。这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。

    通俗说:运行时获得并使用类的信息的方法叫反射

    2.反射的优点与缺点

    优点:

    可以实现动态创建对象和编译,体现出很大的灵活性

    缺点:

    对性能有影响。使用反射基本上是一种解释操作,我们可以告诉JVM,我们希望做什么并且它 满足我们的要求。这类操作总是慢于只直接执行相同的操作。

    概念我写的比较简单,望大家体谅

    实例:

    获得Class对象的办法:

    package com.example;
    
    public class Fruit {
        public String name;
        public static void main(String[] args) throws Exception{
            // TODO Auto-generated method stub
            Fruit f=new Apple();
            System.out.println(f.name);
            //获得Class办法一,通过对象获得
            Class c1=f.getClass();
            System.out.println(c1);
            //只获得类名
            String c2=f.getClass().getSimpleName();
            System.out.println(c2);
            //获得Class办法二,通过字符串获得(包名+类名)
            Class c3=Class.forName("com.example.Apple");
            System.out.println(c3);
            //获得Class办法三,(通过类的静态成员class获得)
            Class c4=Fruit.class;
            System.out.println(c4);
            //获得父类类型
            Class c5=c3.getSuperclass();
            System.out.println(c5);
        }
    
    }
    class Apple extends Fruit{
        public Apple() {
            this.name="苹果";
        }
    }
    
    class Orange extends Fruit{
        public Orange() {
            this.name="橙子";
        }
    }

    结果:

     动态实例化对象示例

    package com.example;
    
    import java.util.Scanner;
    
    public class Fruit {
        public String name;
        public static void main(String[] args) throws Exception{
            // TODO Auto-generated method stub
            Scanner input=new Scanner(System.in);
            System.out.print("请问您要吃点什么?:");
            String type=input.nextLine();
            Class<?> c1=Class.forName("com.example."+type);
            if(c1==null) {
                System.out.println("对不起,这个没有。");
            }else {
                Fruit fruit=(Fruit)c1.newInstance();
                System.out.println("这是您的"+fruit.name+",请慢用。");
            }
        }
    
    }
    class Apple extends Fruit{
        public Apple() {
            this.name="苹果";
        }
    }
    
    class Orange extends Fruit{
        public Orange() {
            this.name="橙子";
        }
    }

    结果:

    这种方式比较动态,比如现在我再加一中水果

    class Peach extends Fruit{
        public Peach() {
            this.name="桃子";
        }
    }

    结果:

    下面有比较完整的实例:

    【案例1】通过一个对象获得完整的包名和类名

    package Reflect;
     
    /**
     * 通过一个对象获得完整的包名和类名
     * */
    class Demo{
        //other codes...
    }
     
    class hello{
        public static void main(String[] args) {
            Demo demo=new Demo();
            System.out.println(demo.getClass().getName());
        }
    }

    【运行结果】:Reflect.Demo

    添加一句:所有类的对象其实都是Class的实例。

    【案例2】实例化Class类对象

    package Reflect;
    class Demo{
        //other codes...
    }
     
    class hello{
        public static void main(String[] args) {
            Class<?> demo1=null;
            Class<?> demo2=null;
            Class<?> demo3=null;
            try{
                //一般尽量采用这种形式
                demo1=Class.forName("Reflect.Demo");
            }catch(Exception e){
                e.printStackTrace();
            }
            demo2=new Demo().getClass();
            demo3=Demo.class;
             
            System.out.println("类名称   "+demo1.getName());
            System.out.println("类名称   "+demo2.getName());
            System.out.println("类名称   "+demo3.getName());
             
        }
    }

    【运行结果】:

    类名称   Reflect.Demo

    类名称   Reflect.Demo

    类名称   Reflect.Demo

    【案例3】通过Class实例化其他类的对象

    通过无参构造实例化对象

    package Reflect;
     
    class Person{
         
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        @Override
        public String toString(){
            return "["+this.name+"  "+this.age+"]";
        }
        private String name;
        private int age;
    }
     
    class hello{
        public static void main(String[] args) {
            Class<?> demo=null;
            try{
                demo=Class.forName("Reflect.Person");
            }catch (Exception e) {
                e.printStackTrace();
            }
            Person per=null;
            try {
                per=(Person)demo.newInstance();
            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            per.setName("Rollen");
            per.setAge(20);
            System.out.println(per);
        }
    }

    【运行结果】:

    [Rollen  20]

    但是注意一下,当我们把Person中的默认的无参构造函数取消的时候,比如自己定义只定义一个有参数的构造函数之后,会出现错误:

    比如我定义了一个构造函数:

    public Person(String name, int age) {
            this.age=age;
            this.name=name;
        }

    然后继续运行上面的程序,会出现:

    java.lang.InstantiationException: Reflect.Person

        at java.lang.Class.newInstance0(Class.java:340)

        at java.lang.Class.newInstance(Class.java:308)

        at Reflect.hello.main(hello.java:39)

    Exception in thread "main" java.lang.NullPointerException

        at Reflect.hello.main(hello.java:47)

    所以大家以后再编写使用Class实例化其他类的对象的时候,一定要自己定义无参的构造函数

    【案例】通过Class调用其他类中的构造函数 (也可以通过这种方式通过Class创建其他类的对象)

    package Reflect;
     
    import java.lang.reflect.Constructor;
     
    class Person{
         
        public Person() {
             
        }
        public Person(String name){
            this.name=name;
        }
        public Person(int age){
            this.age=age;
        }
        public Person(String name, int age) {
            this.age=age;
            this.name=name;
        }
        public String getName() {
            return name;
        }
        public int getAge() {
            return age;
        }
        @Override
        public String toString(){
            return "["+this.name+"  "+this.age+"]";
        }
        private String name;
        private int age;
    }
     
    class hello{
        public static void main(String[] args) {
            Class<?> demo=null;
            try{
                demo=Class.forName("Reflect.Person");
            }catch (Exception e) {
                e.printStackTrace();
            }
            Person per1=null;
            Person per2=null;
            Person per3=null;
            Person per4=null;
            //取得全部的构造函数
            Constructor<?> cons[]=demo.getConstructors();
            try{
                per1=(Person)cons[0].newInstance();
                per2=(Person)cons[1].newInstance("Rollen");
                per3=(Person)cons[2].newInstance(20);
                per4=(Person)cons[3].newInstance("Rollen",20);
            }catch(Exception e){
                e.printStackTrace();
            }
            System.out.println(per1);
            System.out.println(per2);
            System.out.println(per3);
            System.out.println(per4);
        }
    }

    【运行结果】:

    [null  0]

    [Rollen  0]

    [null  20]

    [Rollen  20]

    【案例】 

    返回一个类实现的接口:

    package Reflect;
     
    interface China{
        public static final String name="Rollen";
        public static  int age=20;
        public void sayChina();
        public void sayHello(String name, int age);
    }
     
    class Person implements China{
        public Person() {
             
        }
        public Person(String sex){
            this.sex=sex;
        }
        public String getSex() {
            return sex;
        }
        public void setSex(String sex) {
            this.sex = sex;
        }
        @Override
        public void sayChina(){
            System.out.println("hello ,china");
        }
        @Override
        public void sayHello(String name, int age){
            System.out.println(name+"  "+age);
        }
        private String sex;
    }
     
    class hello{
        public static void main(String[] args) {
            Class<?> demo=null;
            try{
                demo=Class.forName("Reflect.Person");
            }catch (Exception e) {
                e.printStackTrace();
            }
            //保存所有的接口
            Class<?> intes[]=demo.getInterfaces();
            for (int i = 0; i < intes.length; i++) {
                System.out.println("实现的接口   "+intes[i].getName());
            }
        }
    }

    【运行结果】:

    实现的接口   Reflect.China

    (注意,以下几个例子,都会用到这个例子的Person类,所以为节省篇幅,此处不再粘贴Person的代码部分,只粘贴主类hello的代码)

    【案例】:取得其他类中的父类

    class hello{
        public static void main(String[] args) {
            Class<?> demo=null;
            try{
                demo=Class.forName("Reflect.Person");
            }catch (Exception e) {
                e.printStackTrace();
            }
            //取得父类
            Class<?> temp=demo.getSuperclass();
            System.out.println("继承的父类为:   "+temp.getName());
        }
    }

    【运行结果】

    继承的父类为:   java.lang.Object

    【案例】:获得其他类中的全部构造函数

    这个例子需要在程序开头添加import java.lang.reflect.*;

    然后将主类编写为:

    class hello{
        public static void main(String[] args) {
            Class<?> demo=null;
            try{
                demo=Class.forName("Reflect.Person");
            }catch (Exception e) {
                e.printStackTrace();
            }
            Constructor<?>cons[]=demo.getConstructors();
            for (int i = 0; i < cons.length; i++) {
                System.out.println("构造方法:  "+cons[i]);
            }
        }
    }

    【运行结果】:

    构造方法:  public Reflect.Person()

    构造方法:  public Reflect.Person(java.lang.String)

    但是细心的读者会发现,上面的构造函数没有public 或者private这一类的修饰符

    下面这个例子我们就来获取修饰符

    class hello{
        public static void main(String[] args) {
            Class<?> demo=null;
            try{
                demo=Class.forName("Reflect.Person");
            }catch (Exception e) {
                e.printStackTrace();
            }
            Constructor<?>cons[]=demo.getConstructors();
            for (int i = 0; i < cons.length; i++) {
                Class<?> p[]=cons[i].getParameterTypes();
                System.out.print("构造方法:  ");
                int mo=cons[i].getModifiers();
                System.out.print(Modifier.toString(mo)+" ");
                System.out.print(cons[i].getName());
                System.out.print("(");
                for(int j=0;j<p.length;++j){
                    System.out.print(p[j].getName()+" arg"+i);
                    if(j<p.length-1){
                        System.out.print(",");
                    }
                }
                System.out.println("){}");
            }
        }
    }

    【运行结果】:

    构造方法:  public Reflect.Person(){}

    构造方法:  public Reflect.Person(java.lang.String arg1){}

    有时候一个方法可能还有异常,呵呵。下面看看:

    class hello{
        public static void main(String[] args) {
            Class<?> demo=null;
            try{
                demo=Class.forName("Reflect.Person");
            }catch (Exception e) {
                e.printStackTrace();
            }
            Method method[]=demo.getMethods();
            for(int i=0;i<method.length;++i){
                Class<?> returnType=method[i].getReturnType();
                Class<?> para[]=method[i].getParameterTypes();
                int temp=method[i].getModifiers();
                System.out.print(Modifier.toString(temp)+" ");
                System.out.print(returnType.getName()+"  ");
                System.out.print(method[i].getName()+" ");
                System.out.print("(");
                for(int j=0;j<para.length;++j){
                    System.out.print(para[j].getName()+" "+"arg"+j);
                    if(j<para.length-1){
                        System.out.print(",");
                    }
                }
                Class<?> exce[]=method[i].getExceptionTypes();
                if(exce.length>0){
                    System.out.print(") throws ");
                    for(int k=0;k<exce.length;++k){
                        System.out.print(exce[k].getName()+" ");
                        if(k<exce.length-1){
                            System.out.print(",");
                        }
                    }
                }else{
                    System.out.print(")");
                }
                System.out.println();
            }
        }
    }

    【运行结果】:

    public java.lang.String  getSex ()

    public void  setSex (java.lang.String arg0)

    public void  sayChina ()

    public void  sayHello (java.lang.String arg0,int arg1)

    public final native void  wait (long arg0) throws java.lang.InterruptedException

    public final void  wait () throws java.lang.InterruptedException

    public final void  wait (long arg0,int arg1) throws java.lang.InterruptedException

    public boolean  equals (java.lang.Object arg0)

    public java.lang.String  toString ()

    public native int  hashCode ()

    public final native java.lang.Class  getClass ()

    public final native void  notify ()

    public final native void  notifyAll ()

    【案例】接下来让我们取得其他类的全部属性吧,最后我讲这些整理在一起,也就是通过class取得一个类的全部框架

    class hello {
        public static void main(String[] args) {
            Class<?> demo = null;
            try {
                demo = Class.forName("Reflect.Person");
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("===============本类属性========================");
            // 取得本类的全部属性
            Field[] field = demo.getDeclaredFields();
            for (int i = 0; i < field.length; i++) {
                // 权限修饰符
                int mo = field[i].getModifiers();
                String priv = Modifier.toString(mo);
                // 属性类型
                Class<?> type = field[i].getType();
                System.out.println(priv + " " + type.getName() + " "
                        + field[i].getName() + ";");
            }
            System.out.println("===============实现的接口或者父类的属性========================");
            // 取得实现的接口或者父类的属性
            Field[] filed1 = demo.getFields();
            for (int j = 0; j < filed1.length; j++) {
                // 权限修饰符
                int mo = filed1[j].getModifiers();
                String priv = Modifier.toString(mo);
                // 属性类型
                Class<?> type = filed1[j].getType();
                System.out.println(priv + " " + type.getName() + " "
                        + filed1[j].getName() + ";");
            }
        }
    }

    【运行结果】:

    ===============本类属性========================

    private java.lang.String sex;

    ===============实现的接口或者父类的属性========================

    public static final java.lang.String name;

    public static final int age;

    【案例】其实还可以通过反射调用其他类中的方法:

    class hello {
        public static void main(String[] args) {
            Class<?> demo = null;
            try {
                demo = Class.forName("Reflect.Person");
            } catch (Exception e) {
                e.printStackTrace();
            }
            try{
                //调用Person类中的sayChina方法
                Method method=demo.getMethod("sayChina");
                method.invoke(demo.newInstance());
                //调用Person的sayHello方法
                method=demo.getMethod("sayHello", String.class,int.class);
                method.invoke(demo.newInstance(),"Rollen",20);
                 
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    【运行结果】:

    hello ,china

    Rollen  20

    【案例】调用其他类的set和get方法

    class hello {
        public static void main(String[] args) {
            Class<?> demo = null;
            Object obj=null;
            try {
                demo = Class.forName("Reflect.Person");
            } catch (Exception e) {
                e.printStackTrace();
            }
            try{
             obj=demo.newInstance();
            }catch (Exception e) {
                e.printStackTrace();
            }
            setter(obj,"Sex","男",String.class);
            getter(obj,"Sex");
        }
     
        /**
         * @param obj
         *            操作的对象
         * @param att
         *            操作的属性
         * */
        public static void getter(Object obj, String att) {
            try {
                Method method = obj.getClass().getMethod("get" + att);
                System.out.println(method.invoke(obj));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
     
        /**
         * @param obj
         *            操作的对象
         * @param att
         *            操作的属性
         * @param value
         *            设置的值
         * @param type
         *            参数的属性
         * */
        public static void setter(Object obj, String att, Object value,
                Class<?> type) {
            try {
                Method method = obj.getClass().getMethod("set" + att, type);
                method.invoke(obj, value);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }// end class

    【运行结果】:

     【案例】通过反射操作属性

    class hello {
        public static void main(String[] args) throws Exception {
            Class<?> demo = null;
            Object obj = null;
     
            demo = Class.forName("Reflect.Person");
            obj = demo.newInstance();
     
            Field field = demo.getDeclaredField("sex");
            field.setAccessible(true);
            field.set(obj, "男");
            System.out.println(field.get(obj));
        }
    }// end class

    【案例】通过反射取得并修改数组的信息:

    import java.lang.reflect.*;
    class hello{
        public static void main(String[] args) {
            int[] temp={1,2,3,4,5};
            Class<?>demo=temp.getClass().getComponentType();
            System.out.println("数组类型: "+demo.getName());
            System.out.println("数组长度  "+Array.getLength(temp));
            System.out.println("数组的第一个元素: "+Array.get(temp, 0));
            Array.set(temp, 0, 100);
            System.out.println("修改之后数组第一个元素为: "+Array.get(temp, 0));
        }
    }

    【运行结果】:

    数组类型: int

    数组长度  5

    数组的第一个元素: 1

    修改之后数组第一个元素为: 100

    【案例】通过反射修改数组大小

    class hello{
        public static void main(String[] args) {
            int[] temp={1,2,3,4,5,6,7,8,9};
            int[] newTemp=(int[])arrayInc(temp,15);
            print(newTemp);
            System.out.println("=====================");
            String[] atr={"a","b","c"};
            String[] str1=(String[])arrayInc(atr,8);
            print(str1);
        }
         
        /**
         * 修改数组大小
         * */
        public static Object arrayInc(Object obj,int len){
            Class<?>arr=obj.getClass().getComponentType();
            Object newArr=Array.newInstance(arr, len);
            int co=Array.getLength(obj);
            System.arraycopy(obj, 0, newArr, 0, co);
            return newArr;
        }
        /**
         * 打印
         * */
        public static void print(Object obj){
            Class<?>c=obj.getClass();
            if(!c.isArray()){
                return;
            }
            System.out.println("数组长度为: "+Array.getLength(obj));
            for (int i = 0; i < Array.getLength(obj); i++) {
                System.out.print(Array.get(obj, i)+" ");
            }
        }
    }

    【运行结果】:

    数组长度为: 15

    1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 =====================

    数组长度为: 8

    a b c null null null null null

    动态代理

    【案例】首先来看看如何获得类加载器:

    class test{
         
    }
    class hello{
        public static void main(String[] args) {
            test t=new test();
            System.out.println("类加载器  "+t.getClass().getClassLoader().getClass().getName());
        }
    }

    【程序输出】:

    类加载器  sun.misc.Launcher$AppClassLoader

    其实在java中有三种类类加载器。

    1)Bootstrap ClassLoader 此加载器采用c++编写,一般开发中很少见。

    2)Extension ClassLoader 用来进行扩展类的加载,一般对应的是jrelibext目录中的类

    3)AppClassLoader 加载classpath指定的类,是最常用的加载器。同时也是java中默认的加载器。

    如果想要完成动态代理,首先需要定义一个InvocationHandler接口的子类,已完成代理的具体操作。

    package Reflect;
    import java.lang.reflect.*;
     
    //定义项目接口
    interface Subject {
        public String say(String name, int age);
    }
     
    // 定义真实项目
    class RealSubject implements Subject {
        @Override
        public String say(String name, int age) {
            return name + "  " + age;
        }
    }
     
    class MyInvocationHandler implements InvocationHandler {
        private Object obj = null;
     
        public Object bind(Object obj) {
            this.obj = obj;
            return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj
                    .getClass().getInterfaces(), this);
        }
     
        @Override
        public Object invoke(Object proxy, Method method, Object[] args)
                throws Throwable {
            Object temp = method.invoke(this.obj, args);
            return temp;
        }
    }
     
    class hello {
        public static void main(String[] args) {
            MyInvocationHandler demo = new MyInvocationHandler();
            Subject sub = (Subject) demo.bind(new RealSubject());
            String info = sub.say("Rollen", 20);
            System.out.println(info);
        }
    }

    【运行结果】:

    Rollen  20

    类的生命周期

    在一个类编译完成之后,下一步就需要开始使用类,如果要使用一个类,肯定离不开JVM。在程序执行中JVM通过装载,链接,初始化这3个步骤完成。

    类的装载是通过类加载器完成的,加载器将.class文件的二进制文件装入JVM的方法区,并且在堆区创建描述这个类的java.lang.Class对象。用来封装数据。 但是同一个类只会被类装载器装载以前

    链接就是把二进制数据组装为可以运行的状态。

     

    链接分为校验,准备,解析这3个阶段

    校验一般用来确认此二进制文件是否适合当前的JVM(版本),

    准备就是为静态成员分配内存空间,。并设置默认值

    解析指的是转换常量池中的代码作为直接引用的过程,直到所有的符号引用都可以被运行程序使用(建立完整的对应关系)

    完成之后,类型也就完成了初始化,初始化之后类的对象就可以正常使用了,直到一个对象不再使用之后,将被垃圾回收。释放空间。

    当没有任何引用指向Class对象时就会被卸载,结束类的生命周期

    将反射用于工厂模式

    先来看看,如果不用反射的时候,的工厂模式吧:

    /**
     * @author Rollen-Holt 设计模式之 工厂模式
     */
     
    interface fruit{
        public abstract void eat();
    }
     
    class Apple implements fruit{
        public void eat(){
            System.out.println("Apple");
        }
    }
     
    class Orange implements fruit{
        public void eat(){
            System.out.println("Orange");
        }
    }
     
    // 构造工厂类
    // 也就是说以后如果我们在添加其他的实例的时候只需要修改工厂类就行了
    class Factory{
        public static fruit getInstance(String fruitName){
            fruit f=null;
            if("Apple".equals(fruitName)){
                f=new Apple();
            }
            if("Orange".equals(fruitName)){
                f=new Orange();
            }
            return f;
        }
    }
    class hello{
        public static void main(String[] a){
            fruit f=Factory.getInstance("Orange");
            f.eat();
        }
     
    }

    这样,当我们在添加一个子类的时候,就需要修改工厂类了。如果我们添加太多的子类的时候,改的就会很多。

    现在我们看看利用反射机制:

    package Reflect;
     
    interface fruit{
        public abstract void eat();
    }
     
    class Apple implements fruit{
        public void eat(){
            System.out.println("Apple");
        }
    }
     
    class Orange implements fruit{
        public void eat(){
            System.out.println("Orange");
        }
    }
     
    class Factory{
        public static fruit getInstance(String ClassName){
            fruit f=null;
            try{
                f=(fruit)Class.forName(ClassName).newInstance();
            }catch (Exception e) {
                e.printStackTrace();
            }
            return f;
        }
    }
    class hello{
        public static void main(String[] a){
            fruit f=Factory.getInstance("Reflect.Apple");
            if(f!=null){
                f.eat();
            }
        }
    }

    现在就算我们添加任意多个子类的时候,工厂类就不需要修改。

    上面的爱吗虽然可以通过反射取得接口的实例,但是需要传入完整的包和类名。而且用户也无法知道一个接口有多少个可以使用的子类,所以我们通过属性文件的形式配置所需要的子类。

    下面我们来看看: 结合属性文件的工厂模式

    首先创建一个fruit.properties的资源文件,

    内容为:

    apple=Reflect.Apple
    orange=Reflect.Orange

    然后编写主类代码:

    package Reflect;
     
    import java.io.*;
    import java.util.*;
     
    interface fruit{
        public abstract void eat();
    }
     
    class Apple implements fruit{
        public void eat(){
            System.out.println("Apple");
        }
    }
     
    class Orange implements fruit{
        public void eat(){
            System.out.println("Orange");
        }
    }
     
    //操作属性文件类
    class init{
        public static Properties getPro() throws FileNotFoundException, IOException{
            Properties pro=new Properties();
            File f=new File("fruit.properties");
            if(f.exists()){
                pro.load(new FileInputStream(f));
            }else{
                pro.setProperty("apple", "Reflect.Apple");
                pro.setProperty("orange", "Reflect.Orange");
                pro.store(new FileOutputStream(f), "FRUIT CLASS");
            }
            return pro;
        }
    }
     
    class Factory{
        public static fruit getInstance(String ClassName){
            fruit f=null;
            try{
                f=(fruit)Class.forName(ClassName).newInstance();
            }catch (Exception e) {
                e.printStackTrace();
            }
            return f;
        }
    }
    class hello{
        public static void main(String[] a) throws FileNotFoundException, IOException{
            Properties pro=init.getPro();
            fruit f=Factory.getInstance(pro.getProperty("apple"));
            if(f!=null){
                f.eat();
            }
        }
    }

    【运行结果】:Apple

     Q3:注解

    注解的定义

    Annontation是Java5开始引入的新特征,中文名称叫注解。它提供了一种安全的类似注释的机制,用来将任何的信息或元数据(metadata)与程序元素(类、方法、成员变量等)进行关联。为程序的元素(类、方法、成员变量)加上更直观更明了的说明,这些说明信息是与程序的业务逻辑无关,并且供指定的工具或框架使用。Annontation像一种修饰符一样,应用于包、类型、构造方法、方法、成员变量、参数及本地变量的声明语句中。
    Java注解是附加在代码中的一些元信息,用于一些工具在编译、运行时进行解析和使用,起到说明、配置的功能。注解不会也不能影响代码的实际逻辑,仅仅起到辅助性的作用。包含在 java.lang.annotation 包中。

    注解的用处

    1、生成文档。这是最常见的,也是java 最早提供的注解。常用的有@param @return 等

    2、跟踪代码依赖性,实现替代配置文件功能。比如Dagger 2依赖注入,未来java开发,将大量注解配置,具有很大用处;

    3、在编译时进行格式检查。如@override 放在方法前,如果你这个方法并不是覆盖了超类方法,则编译时就能检查出。

    注解的原理

    注解本质是一个继承了Annotation的特殊接口,其具体实现类是Java运行时生成的动态代理类。而我们通过反射获取注解时,返回的是Java运行时生成的动态代理对象$Proxy1。通过代理对象调用自定义注解(接口)的方法,会最终调用AnnotationInvocationHandler的invoke方法。该方法会从memberValues这个Map中索引出对应的值。而memberValues的来源是Java常量池。

    内置注解

    1.)Override

    java.lang.Override是一个标记类型注解,它被用作标注方法。它说明了被标注的方法重载了父类的方法,起到了断言的作用。如果我们使用了这种注解在一个没有覆盖父类方法的方法时,java编译器将以一个编译错误来警示。

    2.)Deprecated

    Deprecated也是一种标记类型注解。当一个类型或者类型成员使用@Deprecated修饰的话,编译器将不鼓励使用这个被标注的程序元素。所以使用这种修饰具有一定的“延续性”:如果我们在代码中通过继承或者覆盖的方式使用了这个过时的类型或者成员,虽然继承或者覆盖后的类型或者成员并不是被声明为@Deprecated,但编译器仍然要报警。

    3.)SuppressWarnings

    SuppressWarning不是一个标记类型注解。它有一个类型为String[]的成员,这个成员的值为被禁止的警告名。对于javac编译器来讲,被-Xlint选项有效的警告名也同样对@SuppressWarings有效,同时编译器忽略掉无法识别的警告名。
    @SuppressWarnings("unchecked"

    元注解

    java.lang.annotation提供了四种元注解,专门注解其他的注解(在自定义注解的时候,需要使用到元注解):
    @Documented –注解是否将包含在JavaDoc中
    @Retention –什么时候使用该注解
    @Target –注解用于什么地方
    @Inherited – 是否允许子类继承该注解

    1.)@Retention– 定义该注解的生命周期

    ● RetentionPolicy.SOURCE : 在编译阶段丢弃。这些注解在编译结束之后就不再有任何意义,所以它们不会写入字节码。@Override, @SuppressWarnings都属于这类注解。
    ● RetentionPolicy.CLASS : 在类加载的时候丢弃。在字节码文件的处理中有用。注解默认使用这种方式
    ● RetentionPolicy.RUNTIME : 始终不会丢弃,运行期也保留该注解,因此可以使用反射机制读取该注解的信息。我们自定义的注解通常使用这种方式。

    非常关键,默认设置反射是获取不到的,设置成RUNTIME在运行时可以获取

    2.)Target – 表示该注解用于什么地方

    默认值为任何元素,表示该注解用于什么地方。可用的ElementType参数包括

    ● ElementType.CONSTRUCTOR:用于描述构造器
    ● ElementType.FIELD:成员变量、对象、属性(包括enum实例)
    ● ElementType.LOCAL_VARIABLE:用于描述局部变量
    ● ElementType.METHOD:用于描述方法
    ● ElementType.PACKAGE:用于描述包
    ● ElementType.PARAMETER:用于描述参数
    ● ElementType.TYPE:用于描述类、接口(包括注解类型) 或enum声明

    3.)@Documented–表示是否将注解信息添加在java文档中

    4.)@Inherited – 定义该注释和子类的关系

    @Inherited 元注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。

    自定义注解

    自定义注解类编写的一些规则:
    1. Annotation型定义为@interface, 所有的Annotation会自动继承java.lang.Annotation这一接口,并且不能再去继承别的类或是接口。

    2. 参数成员只能用public或默认(default)这两个访问权修饰

    3. 参数成员只能用基本类型byte,short,char,int,long,float,double,boolean八种基本数据类型和String、Enum、Class、annotations等数据类型,以及这一些类型的数组.

    4. 要获取类方法和字段的注解信息,必须通过Java的反射技术来获取 Annotation对象,因为你除此之外没有别的获取注解对象的方法

    5. 注解也可以没有定义成员,自定义注解需要使用到元注解

    自定义注解实例(结合反射)

    User

    package com.tables;
    /**
     *  java注解样例   利用注解将此表映射到数据库的表
     *  @author 张育威
     * */
    @Table("user")
    public class User {
        //定义字段属性
        private int id;
        private String username;
        private String age;
        private String city;
        public User() {}
        public User(int id, String username, String age, String city) {
            super();
            this.id = id;
            this.username = username;
            this.age = age;
            this.city = city;
        }
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getUsername() {
            return username;
        }
        public void setUsername(String username) {
            this.username = username;
        }
        public String getAge() {
            return age;
        }
        public void setAge(String age) {
            this.age = age;
        }
        public String getCity() {
            return city;
        }
        public void setCity(String city) {
            this.city = city;
        }
    }

    Table

    package com.tables;
    
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    /**
     * 数据表的直接
     * @author 
     * */
    //@Retention– 定义该注解的生命周期
    @Retention(RetentionPolicy.RUNTIME)
    //Target – 表示该注解用于什么地方
    @Target({ElementType.TYPE})
    public @interface Table {
        String value();//表名
    }

    Text

    package com.tables;
    
    import java.lang.reflect.Field;
    
    public class Text {
    
        public static void main(String[] args) throws Exception{
            // TODO Auto-generated method stub
            Query();
        }    
        public static void Query() throws Exception{
            //把数据存储到StringBuilder中
            StringBuilder sql = new StringBuilder();
            //获取Class
            Class c1=Class.forName("com.tables.User");
            //获取table的名字
            //判断注解是否存在
            String tableName=null;
            boolean b=c1.isAnnotationPresent(Table.class);
            if(!b) {
                tableName=c1.getSimpleName();//User
            }else {
                //获取注解中的表名
                Table t=(Table) c1.getAnnotation(Table.class);
                tableName=t.value();//user
            }
            //获取字段的属性
            Field[] filed=c1.getDeclaredFields();
            //System.out.println(filed[0].getName());//id
            //获取字段的类型
            //System.out.println(filed[0].getType().getSimpleName());//int
            //System.out.println(filed.length);//4
            //insert into user(id,username,age,city) vlaues(1,'老张',19,'珠海')
            sql.append("insert into "+tableName+"(");
            for(int i=0;i<filed.length;i++) {
                if(i<3) {
                    sql.append(filed[i].getName()+",");
                }else {
                    sql.append(filed[i].getName());
                }
            }
            sql.append(") values(1,'老张',19,'珠海')");
            System.out.println(sql);
        }
        
    }

    结果

     提示:我只是做了一个添加,还有其他的,最主要的是类型与数据库类型不同,类型之间的转换我暂时就不写了,有时间的话我会将其贴上,

    zywds
  • 相关阅读:
    人类历史上最智慧的169条警世箴言(句句珠玑,发人深省)
    最负责任的回答
    成大事必须依靠的五种人
    一生的伤痕
    有谁愿意陪我一程
    惜缘
    那朵美丽的格桑花,你是否依然绽放?
    今生今世只等你
    成就一生的15条黄金法则
    遇到困难挫折也不要悲观:每个人生来就是冠军(转)
  • 原文地址:https://www.cnblogs.com/zywds/p/9370107.html
Copyright © 2011-2022 走看看