使用反射来保存onClick()函数
try {
Method method = getClass().getMethod("onClick", View.class);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface SaveOnClick {}
@SaveOnClick
public void onClick(View view) {
// 在这里添加 onClick() 方法的逻辑
}
public class AnnotationUtil {
public static void saveOnClick(Object object) {
Method[] methods = object.getClass().getMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(SaveOnClick.class)) {
try {
Method m = object.getClass().getMethod("onClick", View.class);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AnnotationUtil.saveOnClick(this);
}