標籤:
最近在看React-native,對內部實現高度興趣,自己寫了Module註冊進去,並且在js中調用,很好奇自己的方法是怎麼暴露給js的,看了BaseJavaModule的源碼,裡面有方法是如何暴露的。
@Overridepublic final Map<String, NativeMethod> getMethods() { Map<String, NativeMethod> methods = new HashMap<String, NativeMethod>(); Method[] targetMethods = getClass().getDeclaredMethods(); for (int i = 0; i < targetMethods.length; i++) { Method targetMethod = targetMethods[i]; //找有@ReactMethod註解的方法 if (targetMethod.getAnnotation(ReactMethod.class) != null) { String methodName = targetMethod.getName(); if (methods.containsKey(methodName)) { // We do not support method overloading since js sees a function as an object regardless // of number of params. throw new IllegalArgumentException( "Java Module " + getName() + " method name already registered: " + methodName); } methods.put(methodName, new JavaMethod(targetMethod)); } } return methods;}
React-native Android Java Module如何暴露自己的方法給js