现在准备研究一些源码或者框架,但是一些基础的知识一定要懂,不然没法看,比如设计模式,java基础中的反射,泛型,注解,多线程,线程池,队列等,现在很多框架都是这些知识杂糅而成的,
我们常用的java内置三大注解:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
上面onCreate()方法上@Override就是注解,我们点击进去看看,
package java.lang;
import java.lang.annotation.*;
/**
* Indicates that a method declaration is intended to override a
* method declaration in a supertype. If a method is annotated with
* this annotation type compilers are required to generate an error
* message unless at least one of the following conditions hold:
*
* <ul><li>
* The method does override or implement a method declared in a
* supertype.
* </li><li>
* The method has a signature that is override-equivalent to that of
* any public method declared in {@linkplain Object}.
* </li></ul>
*
* @author Peter von der Ahé
* @author Joshua Bloch
* @jls 9.6.1.4 Override
* @since 1.5
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
@interface就是表明声明一个注解类,在java.lang包下,发现声明的注解Override上面有2个@Target和@Retention这二个注解,
@Target(ElementType.METHOD) 表示注解类(Override)使用再方法上
@Retention(RetentionPolicy.SOURCE) 表示使用再源码中
@Target说明了Annotation所修饰的对象范围
再点击Target进去看看:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
ElementType[] value();
}
我们发现
@Target(ElementType.ANNOTATION_TYPE)
()这个括号里的是啥东西呢,还是点击进去看看源码:
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
TYPE,
/** Field declaration (includes enum constants) */
FIELD,
/** Method declaration */
METHOD,
/** Formal parameter declaration */
PARAMETER,
/** Constructor declaration */
CONSTRUCTOR,
/** Local variable declaration */
LOCAL_VARIABLE,
/** Annotation type declaration */
ANNOTATION_TYPE,
/** Package declaration */
PACKAGE,
/**
* Type parameter declaration
*
* @since 1.8
* @hide 1.8
*/
TYPE_PARAMETER,
/**
* Use of a type
*
* @since 1.8
* @hide 1.8
*/
TYPE_USE
}
这是JDK1.5后出来的,也就是说1.5之前是没注解的,ElementType 这是一个枚举类,这个枚举类中定义了10个变量,哪这10个变量都是啥意思呢?
@Target(ElementType.TYPE) //接口、类、枚举、注解
@Target(ElementType.FIELD) //字段、枚举的常量
@Target(ElementType.METHOD) //方法
@Target(ElementType.PARAMETER) //方法参数
@Target(ElementType.CONSTRUCTOR) //构造函数
@Target(ElementType.LOCAL_VARIABLE)//局部变量
@Target(ElementType.ANNOTATION_TYPE)//注解
@Target(ElementType.PACKAGE) ///包
Target注解类中还有一个声明注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
RetentionPolicy value();
}
@Retention
表示注解的作用时段
1.SOURCE:在源文件中有效(即源文件保留)
2.CLASS:在class文件中有效(即class保留)
3.RUNTIME:在运行时有效(即运行时保留)
public enum RetentionPolicy {
/**
* Annotations are to be discarded by the compiler.
*/
SOURCE,
/**
* Annotations are to be recorded in the class file by the compiler
* but need not be retained by the VM at run time. This is the default
* behavior.
*/
CLASS,
/**
* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.
*
* @see java.lang.reflect.AnnotatedElement
*/
RUNTIME
}
源码中RetentionPolicy 也是一个枚举类,定义了三个变量
java内置三大注解:
1:@Override
定义在java.lang.Override中,此注解只适应于修饰方法,表示一个方法声明打算重写超类(父类)的另一个方法声明
package com.annotation;
/**
* Created by admin on 2017/1/10.
*/
public interface Person {
String getName();
int getAge();
void sing();
}
这是我们自己写的一个接口,
package com.annotation;
/**
* Created by admin on 2017/1/10.
*/
public class Child implements Person {
@Override
public String getName() {
return null;
}
@Override
public int getAge() {
return 0;
}
@Override
public void sing() {
}
}
我们发现Child实现了Person接口,getName(),getAge(),sing()方法上都有@Override注解,表明这三个方法都是来自接口Person
2:@Deprecated
定义在java.lang.Deprecated中,此注解可修饰类,方法,属性,表示不建议程序员使用这个方法,属性,类等,表示它已过时,有更好的选择或者存在危险,下面我是我平时开发中很常见的过时警告:
3:@SuppressWarnings中,用来拟制编译时警告信息,下面的代码也是很常见的
哪怎么修复呢?有二种,一种是按照提示去补充代码,比如List要添加泛型,表示这个list存储的是什么类型的数据,还有一种就是使用注解,
这个警告信息就没了,
放在变量前面也行:
在jdk源码中这个注解也到处都是
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
/**
* The set of warnings that are to be suppressed by the compiler in the
* annotated element. Duplicate names are permitted. The second and
* successive occurrences of a name are ignored. The presence of
* unrecognized warning names is <i>not</i> an error: Compilers must
* ignore any warning names they do not recognize. They are, however,
* free to emit a warning if an annotation contains an unrecognized
* warning name.
*
* <p>Compiler vendors should document the warning names they support in
* conjunction with this annotation type. They are encouraged to cooperate
* to ensure that the same names work across multiple compilers.
*/
String[] value();
}
String[] value();我刚开始以为是方法,后来发现理解错了,value是参数名,String[]是参数类型,
如果想要使用这个注解,就必须至少添加一个参数,这些参数值都是定义好的,如下:
比如这么使用:
如果只有一个参数的话可以这么使用
@SuppressWarnings("all")
如果是多个参数的话,这么使用:
@SuppressWarnings(value={"all","unchecked"})
自定义注解:
使用@interface自定义注解时,自动继承了java.lang.annotatin.Annotation
@interface用来声明一个注解
格式:public @interface 注解名
其中每一个方法其实是声明一个配置参数,就和我们上面讲的SuppressWarnings一样,
方法的名称就是参数的名称
返回值类型就是参数的类型(返回值类型只能是基本类型,Class,String,enum)
可以通过default来声明参数的默认值
如果只有一个参数成员,一般参数名为value.
如果一个注解中什么都没有的话就是一个标记注解,比如:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
没有定义参数和参数类型,
在android studio中定义一个注解类:在这里选择,
package com.annotation;
/**
* Created by admin on 2017/1/11.
*/
public @interface MyAnnotation {
}
它默认是继承了Annotation,就像你随便定义一个Person,它也是隐士的继承了Object类一样,
一般定义注解都要在这个注解上定义2个元注解,那么什么是元注解呢?
元注解:
元注解的作用就是负责注解其他的注解,对注解进行描述,java定义了4个标注的meta-annotation类型,他们被用来对其他Annotation类型的说明,分别有如下四个:
@Target:用于描述注解的使用范围(也就是说注解可以被用在什么地方),
public @interface Target {
ElementType[] value();
}
它是有参数名和参数类型的,上面已说明了,在这就不描述了
@Retention:表示在什么级别保存该注释信息,用于描述注解的生命周期
一般都是使用RUNTIME,因为你自定义注解肯定是希望通过反射在运行时读取啊,而前二者通知是在编译时期,如果使用了RUNTIME,那么就包含前二者,因为它生命周期最长,如果定义了前二者反射是读取不到的.
@Documented:Documented 注解表明这个注解应该被 javadoc工具记录. 默认情况下,javadoc是不包括注解的. 但如果声明注解时指定了 @Documented,则它会被 javadoc 之类的工具处理, 所以注解类型信息也会被包括在生成的文档中
现在在eclipse中如何演示生成一个文档:
第一步点击项目:选择Export
第二步:
第三步:
第四步:在eclipse下运行生成文档
第五步:在之前选择存放文档的目录中找到生成的文档:
看到这个相信大家都明白了,jdk中文或者英文文档是不是有这个了,然后点击index.html查看
@Inherited:允许子类继承父类的注解
上面把元注解讲完了,现在自定义注解:
package com.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by admin on 2017/1/11.
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String name();
}
解释:
使用:
发现报错了,解决这种办法有二个方法
第一个方法:
设置默认值:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String name() default "";
}
第二种方法:
public class Test {
@MyAnnotation(name="zhou")
public void test(){
}
}
这就是自定义注解了,我写的是一个简单的,其实复杂的也就是所谓的参数多点而已,
使用反射读取注解内容
写这个例子就是使用注解和反射知识动态的生成一条sql语句,现在很多框架估计也是这么干的,只是猜想,没看过网上那些三方数据库框架的源码,
package com.annotation;
/**
* Created by admin on 2017/1/11.
*/
@UserAnnotion("table_user")
public class User {
@AttrsAnnotation(columnName = "id",type ="int",len = 10)
private int id;
@AttrsAnnotation(columnName = "name",type ="varchar",len = 10)
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
对类名进行注解跟表名进行xiangguan
package com.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by admin on 2017/1/11.
*/
@Target(value= {ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface UserAnnotion {
String value();//与表名对应
}
类中的属性和表字段进行相关联通过注解的方式
package com.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 修饰表中属性的注解
* Created by admin on 2017/1/11.
*/
@Target(value= {ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface AttrsAnnotation {
String columnName() default "";
String type() default "";
int len() default 10;
}
最终动态的生成sql语句:
/**
* 读取User中的数据 动态生成sql语句
*/
public void table(){
try {
Class clazz = Class.forName("com.annotation.User");
if(clazz!=null){
UserAnnotion userAnnotion = (UserAnnotion) clazz.getAnnotation(UserAnnotion.class);
String table_name = userAnnotion.value();//获取表名
Field nameFiled = clazz.getDeclaredField("name");
Field idFiled = clazz.getDeclaredField("id");
AttrsAnnotation nameFiledAnnotation = nameFiled.getAnnotation(AttrsAnnotation.class);
AttrsAnnotation idFiledAnnotation = idFiled.getAnnotation(AttrsAnnotation.class);
String tabpPre = "CREATE TABLE IF NOT EXISTS ";
String sql=tabpPre+table_name+"("+"_id INTEGER PRIMARY KEY AUTOINCREMENT"+","+nameFiledAnnotation.columnName()+" "+nameFiledAnnotation.type()+"("+nameFiledAnnotation.len()+")"+","+idFiledAnnotation.columnName()+" "+idFiledAnnotation.type()+")";
Log.e(TAG,"SQL="+sql);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
结果:
CREATE TABLE IF NOT EXISTS table_user(_id INTEGER PRIMARY KEY AUTOINCREMENT,name varchar(10),id int)
如图调用:
如果知道这些理论,以后看三方数据库框架应该轻松很多的,就写到这吧