1. Reflection
Role: to do things that can't be done normally
Usage scenarios: plug-in skinning, plug-in development
All reflection functions are based on class bytecode, which consists of three parts
- Filed: Properties
- Constructor: constructor
- method: method
public class TestBean { private String name="xiaoming";//属性 public TestBean(String name,int age){// 构造函数 this.name = name; } public void sysName(){//方法 Log.e("TAG",name); } private void say(String desc){ Log.e("TAG",name + " : "+desc); } }
constructor call
try { Constructor<TestBean> constructor = TestBean.class.getDeclaredConstructor(String.class, int.class); constructor.setAccessible(true); TestBean testBean = constructor.newInstance("名称", 18); testBean.sysName(); } catch (Exception e) { e.printStackTrace(); }
TestBean testBean = TestBean.class.newInstance(parameter type);
getDeclaredConstructor finds from all constructors
getConstructor finds from public constructorsconstructor.setAccessible(true);//Set permissions
method call
Method method = TestBean.class.getDeclaredMethod("say",String.class); method.setAccessible(true); method.invoke(constructor,"描述信息");
attribute call
Field field = TestBean.class.getDeclaredField("name"); field.setAccessible(true); String name = (String) field.get(testBean);
2. Notes
Annotation is just an identifier and has no specific function
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ViewById {// @interface 代表注解
int value();
}
@Target: where to put it
- ElementType.METHOD: acts on the method
- ElementType.Type: acts on the class
- ElementType.Field: acting on attributes
@Retention:
- RetentionPolicy.RUNTIME: runtime, such as: xUtils
- RetentionPolicy.CLASS: compile time (package time), such as: ButterKnife
- RetentionPolicy.SOURCE: While programming
Annotation combined with reflection solves findViewById injection
public class ViewUtils {
public static void inject(Activity activity) {
// 1.获取所有的属性
Field[] fields = activity.getClass().getDeclaredFields();
// 2.过滤关于 ViewById 属性
for (Field field : fields) {
ViewById viewById = field.getAnnotation(ViewById.class);
if(viewById != null){
// 3.findViewById
View view = activity.findViewById(viewById.value());
// 4.反射注入
field.setAccessible(true);
try {
// activity 属性所在类,view 代表的是属性的值
field.set(activity,view);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
}
3. Generics
Class generic: appearing anywhere, representing the same type
Method Generics: acting on methods
Upper limit: class name <? extends class> object name class and its subclasses
Lower limit: class name <? super class> object name class and its parent class