简单反射与注解(findviewbyid)

MainActivity

package com.bawei.annotationandreflexdemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.bawei.annotationandreflexdemo.annotation.InjectViewAnnotation;
import com.bawei.annotationandreflexdemo.annotation.InjectViewParser;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * @author hasee
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    @InjectViewAnnotation(R.id.check_reflex)
    Button mButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        InjectViewParser.bind(this);
        initView();
    }

    private void initView() {
        mButton.setOnClickListener(this);
        findViewById(R.id.reflex_with_parameter).setOnClickListener(this);
        findViewById(R.id.reflex_with_no_parameter).setOnClickListener(this);
    }


    private void reflexDemoBean() throws ClassNotFoundException, IllegalAccessException, NoSuchMethodException {
        DemoBean demoBean = new DemoBean();
        Class c = Class.forName(demoBean.getClass().getCanonicalName());
        // 获取所有的变量
        Field[] fields = c.getDeclaredFields();
        StringBuffer sb = new StringBuffer();
        sb.append(Modifier.toString(demoBean.getClass().getModifiers()) + " class " + demoBean.getClass().getSimpleName() + "{\n");
        // 遍历每一个变量
        for (Field field : fields) {
            field.setAccessible(true);
            // 获得变量的修饰符,例如public,static等等
            sb.append(Modifier.toString(field.getModifiers()) + " ");
            // 变量的类型的名字
            sb.append(field.getType().getSimpleName() + " ");
            // 变量的名字
            sb.append(field.getName() + ";\n");

            field.set(demoBean, "aaaaaaaaaaaaaaaaaaaaaaaaaaa");
            Object o = field.get(demoBean);
            if (o instanceof String) {
                String str = String.valueOf(o);
                sb.append(str + ";\n");
            }
        }
        sb.append("}\n");
        System.out.println("--------------------------------------------------------------------");
        System.out.println(sb);

        //获得构造方法
        Constructor<?> cons = c.getConstructor();
        System.out.println("--------------------------------------------------------------------");
        System.out.println("构造方法方法名:" + cons.getName());
        System.out.println("构造方法修饰符:" + Modifier.toString(cons.getModifiers()));
        System.out.println("构造方法全部:" + cons);


        // 获取所有的方法
        //public Method[] getMethods()返回某个类的所有公用(public)方法包括其继承类的公用方法,当然也包括它所实现接口的方法。
        //public Method[] getDeclaredMethods()对象表示的类或接口声明的所有方法,包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法。当然也包括它所实现接口的方法。
        Method[] methods = c.getDeclaredMethods();
        for (int i = 0; i < methods.length; i++) {
            System.out.println("--------------------------------------------------------------------");
            System.out.println("方法名:" + methods[i].getName());
            System.out.println("方法返回类型:" + methods[i].getReturnType());
            System.out.println("方法访问修饰符:" + Modifier.toString(methods[i].getModifiers()));
            System.out.println("方法代码写法: " + methods[i]);
        }
    }

    private void doReflexWithParameter() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        DemoBean demoBean = new DemoBean();

        System.out.println("\n changeStr(String str):");
        System.out.println("调用前: " + demoBean.getStr());
        Method method = demoBean.getClass().getDeclaredMethod("changeStr123", String.class);
        method.setAccessible(true);
        Object o = method.invoke(demoBean, "str has changed");
        if(o instanceof String){
            System.out.println("调用后: " + String.valueOf(o));
        }
//        System.out.println("调用后: " + demoBean.getStr());
    }

    private void doReflexWithNoParameter() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        DemoBean demoBean = new DemoBean();

        System.out.println("\n changeStr(String str):");
        System.out.println("调用前: " + demoBean.getStr());
        Method method = demoBean.getClass().getDeclaredMethod("initStr");
        method.setAccessible(true);
        method.invoke(demoBean);
        System.out.println("调用后: " + demoBean.getStr());
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.check_reflex:
                try {
                    reflexDemoBean();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.reflex_with_parameter:
                try {
                    doReflexWithParameter();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.reflex_with_no_parameter:
                try {
                    doReflexWithNoParameter();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }
}

注解

package com.bawei.annotationandreflexdemo.annotation;

import android.support.annotation.IdRes;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.RetentionPolicy.*;

@Retention(RUNTIME)
@Target(ElementType.FIELD)
public @interface InjectViewAnnotation {
    @IdRes int value();
}

注解解析

package com.bawei.annotationandreflexdemo.annotation;

import android.app.Activity;
import android.view.View;

import java.lang.reflect.Field;

/**
 * 注解解析
 * @author hasee
 */
public class InjectViewParser {
    public static void bind(Object object) {
        try {
            parse(object);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void parse(Object object) throws Exception {
        final Class<?> clazz = object.getClass();
        View view = null;
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(InjectViewAnnotation.class)) {
                InjectViewAnnotation injectView = field.getAnnotation(InjectViewAnnotation.class);
                int id = injectView.value();
                if (id < 0) {
                    throw new Exception("error");
                } else {
                    field.setAccessible(true);
                    if (object instanceof View) {
                        view = ((View) object).findViewById(id);
                    } else if (object instanceof Activity) {
                        view = ((Activity) object).findViewById(id);
                    }
                    field.set(object, view);
                }
            }
        }
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值