@ReactMethod用来修饰供JS调用的原生方法
JS的参数转为JAVA的参数就是个问题了,都有哪些类型可以转换?
在JavaMethodWrapper类中的buildArgumentExtractors方法中做了判断,源码如下:
private ArgumentExtractor[] buildArgumentExtractors(Class[] paramTypes) {
ArgumentExtractor[] argumentExtractors =new ArgumentExtractor[paramTypes.length];
for (int i =0; i < paramTypes.length; i += argumentExtractors[i].getJSArgumentsNeeded()) {
Class argumentClass = paramTypes[i];
if (argumentClass == Boolean.class || argumentClass ==boolean.class) {
argumentExtractors[i] =ARGUMENT_EXTRACTOR_BOOLEAN;
}else if (argumentClass == Integer.class || argumentClass ==int.class) {
argumentExtractors[i] =ARGUMENT_EXTRACTOR_INTEGER;
}else if (argumentClass == Double.class || argumentClass ==double.class) {
argumentExtractors[i] =ARGUMENT_EXTRACTOR_DOUBLE;
}else if (argumentClass == Float.class || argumentClass ==float.class) {
argumentExtractors[i] =ARGUMENT_EXTRACTOR_FLOAT;
}else if (argumentClass == String.class) {
argumentExtractors[i] =ARGUMENT_EXTRACTOR_STRING;
}else if (argumentClass == Callback.class) {
argumentExtractors[i] =ARGUMENT_EXTRACTOR_CALLBACK;
}else if (argumentClass == Promise.class) {
argumentExtractors[i] =ARGUMENT_EXTRACTOR_PROMISE;
Assertions.assertCondition(
i == paramTypes.length -1,"Promise must be used as last parameter only");
}else if (argumentClass == ReadableMap.class) {
argumentExtractors[i] =ARGUMENT_EXTRACTOR_MAP;
}else if (argumentClass == ReadableArray.class) {
argumentExtractors[i] =ARGUMENT_EXTRACTOR_ARRAY;
}else if (argumentClass == Dynamic.class) {
argumentExtractors[i] =ARGUMENT_EXTRACTOR_DYNAMIC;
}else {
throw new RuntimeException(
"Got unknown argument class: " + argumentClass.getSimpleName());
}
}
return argumentExtractors;
}
从中可以清晰的看到,boolean,int,double,float,String这些java的基本值类型都可以转,
其他可转类都是RN自己实现的,包括Callback,Promise,ReadableMap,ReadableArray,Dynamic类,其中比较常用的是
ReadableMap,ReadableArray,对应java的Map和List,都有函数直接转为HashMap和ArrayList,
Callback是回调方法,
Promise对应JS的Promise方法,
Dynamic则是一个灵活类,这样JS可以传不用类型的参数,再由JAVA通过Dynamic的方法自己判断是那种类型的数据再做转换。
网友评论