1.@在Android中的作用?
(1)和編譯器一起給你一些提示警告信息。
(2)快捷有效的編譯Java代碼,谷歌出的support-annotations這個庫 就是主要干這個的。
(3)和反射一起 提供一些類似于spring 可配置的功能,方便簡潔.
http://tools.android.com/tech-docs/support-annotations (谷歌官方注解庫文檔)
2.一個簡單的用法,@Nullable (可為空) 和 @NonNull(不能為空)。
private string hello(@NonNull String s){
return " " ;
}
調(diào)用hello這個方法;
String s = null;
hello(s);
運行后會出現(xiàn)這個警告;
1 Argument 'a' might be null less... (Ctrl+F1)
2 This inspection analyzes method control and data flow to report possible conditions that are always true or false, expressions whose value is statically proven to be constant, and situations that can lead to nullability contract violations.
3 Variables, method parameters and return values marked as @Nullable or @NotNull are treated as nullable (or not-null, respectively) and used during the analysis to check nullability contracts, e.g. report possible NullPointerException errors.
4 More complex contracts can be defined using @Contract annotation, for example:
5 @Contract(", null -> null") — method returns null if its second argument is null @Contract(", null -> null; _, !null -> !null") — method returns null if its second argument is null and not-null otherwise @Contract("true -> fail") — a typical assertFalse method which throws an exception if true is passed to it
6 The inspection can be configured to use custom @Nullable
7 @NotNull annotations (by default the ones from annotations.jar will be used)
這里出現(xiàn)警告是因為你所傳入的值為空,但在注解里面已經(jīng)處理,所以你看到的只是警告,而不是NullPointerException errors.
從這里就可以看出來@的方便性了吧.
http://www.cnblogs.com/punkisnotdead/p/3384464.html(反射的鏈接)
3.一個仿照Butterknife案例
(1).首先定義一個InjectView注解
package com.example.administrator.testfab;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by Administrator on 2015/8/5.
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface InjectView {
//id就表示哪些控件,-1就表示取不到時候的默認(rèn)值
int id() default -1;
}
(2)然后定義一個解釋器
1 package com.example.administrator.testfab;
2
3 import android.app.Activity;
4 import android.view.View;
5
6 import java.lang.reflect.Field;
7
8 /**
9 * Created by Administrator on 2015/8/5.
10 */
11 public class InjectViewParser {
12
13 public static void inject(Object object) {
14
15 try {
16 parse(object);
17 } catch (Exception e) {
18 e.printStackTrace();
19 }
20 }
21
22 public static void parse(Object object) throws Exception {
23 final Class<?> clazz = object.getClass();
24 View view = null;
25 Field[] fields = clazz.getDeclaredFields();
26 for (Field field : fields) {
27 if (field.isAnnotationPresent(InjectView.class)) {
28 InjectView injectView = field.getAnnotation(InjectView.class);
29 int id = injectView.id();
30 if (id < 0) {
31 throw new Exception("id must not be null");
32 } else {
33 field.setAccessible(true);
34 if (object instanceof View) {
35 view = ((View) object).findViewById(id);
36 } else if (object instanceof Activity) {
37 view = ((Activity) object).findViewById(id);
38 }
39 field.set(object, view);
40 }
41
42 }
43
44 }
45
46 }
47 }
(3)最后在actity里使用即可;
1 package com.example.administrator.testfab;
2
3 import android.os.AsyncTask;
4 import android.os.Bundle;
5 import android.support.annotation.CallSuper;
6 import android.support.annotation.NonNull;
7 import android.support.annotation.Nullable;
8 import android.support.annotation.StringRes;
9 import android.support.v7.app.AppCompatActivity;
10 import android.util.Log;
11 import android.view.Menu;
12 import android.view.MenuItem;
13 import android.widget.Button;
14
15 public class MainActivity extends AppCompatActivity {
16
17 @InjectView(id = R.id.bt)
18 private Button bt;
19
20
21 @Override
22 protected void onCreate(Bundle savedInstanceState) {
23 super.onCreate(savedInstanceState);
24 setContentView(R.layout.activity_main);
25 //開始注入
26 InjectViewParser.inject(this);
27 //這個主要是測試注入id 成功沒有 成功了就不會報錯~
28 bt.setText("inject done");
29
30
31 }
32
33
34 @Override
35 public boolean onCreateOptionsMenu(Menu menu) {
36 // Inflate the menu; this adds items to the action bar if it is present.
37 getMenuInflater().inflate(R.menu.menu_main, menu);
38 return true;
39 }
40
41 @Override
42 public boolean onOptionsItemSelected(MenuItem item) {
43 // Handle action bar item clicks here. The action bar will
44 // automatically handle clicks on the Home/Up button, so long
45 // as you specify a parent activity in AndroidManifest.xml.
46 int id = item.getItemId();
47
48 //noinspection SimplifiableIfStatement
49 if (id == R.id.action_settings) {
50 return true;
51 }
52
53 return super.onOptionsItemSelected(item);
54 }
55
56
57
58 }