昨天写了一篇PermissionsDispatcher初探,文章最后说要用java重写processor模块,今天花了半天时间完成,现在把代码放在github上:https://github.com/ileelay/PermissionsDispatcher/tree/2.2.0j,欢迎大家纠正!同时感慨到Kotlin太强大,Java太繁琐;
虽然Kotlin语法很简练,终究还是基于JVM,同时这篇文章不是循序渐进的Kotlin语法讲解,只是为了记录在转PermissionsDispatcher时的粗略见解;
普通class
kotlin是这样子写的1
class NoParametersAllowedException(e: ExecutableElement) : RuntimeException("Method '${e.simpleString()}()' must not have any parameters")
为了保持参数一致,我用java是这样写的:1
2
3
4
5
6
7
8
9
10
11public class NoParametersAllowedException extends RuntimeException {
public static RuntimeException getInstance(ExecutableElement e) {
return new NoParametersAllowedException("Method "+e.getSimpleName().toString()+" must not have any parameters");
}
private NoParametersAllowedException(String s) {
super(s);
}
}
常量的定义
kotlin这样1
2
3
4
5
6
7
8//Constants.kt
val FILE_COMMENT = "This file was generated by PermissionsDispatcher. Do not modify!"
val GEN_CLASS_SUFFIX = "PermissionsDispatcher"
val GEN_REQUESTCODE_PREFIX = "REQUEST_"
val GEN_PERMISSION_PREFIX = "PERMISSION_"
val GEN_PENDING_PREFIX = "PENDING_"
val GEN_WITHCHECK_SUFFIX = "WithCheck"
val GEN_PERMISSIONREQUEST_SUFFIX = "PermissionRequest"
说实话,kotlin这样写好变态,连class关键字都不用声明,我用java也尽量保持简洁,可还是比不过它;1
2
3
4
5
6
7
8
9public interface Constants {
String FILE_COMMENT = "This file was generated by PermissionsDispatcher. Do not modify!";
String GEN_CLASS_SUFFIX = "PermissionsDispatcher";
String GEN_REQUESTCODE_PREFIX = "REQUEST_";
String GEN_PERMISSION_PREFIX = "PERMISSION_";
String GEN_PENDING_PREFIX = "PENDING_";
String GEN_WITHCHECK_SUFFIX = "WithCheck";
String GEN_PERMISSIONREQUEST_SUFFIX = "PermissionRequest";
}
Extensions
1 | //Extensions.kt |
###
这个用java写就比较尴尬了,我是用工具类,功能可以实现,但还是没法保持统一的调用方式;
1 | //Extensions.java |
初始化一个List
1 | processorUnits = listOf(ActivityProcessorUnit(),SupportFragmentProcessorUnit(),NativeFragmentProcessorUnit()) |
用java咋写,尴尬了1
2
3
4processorUnits = new ArrayList<ProcessorUnit>();
processorUnits.add(new ActivityProcessorUnit());
processorUnits.add(new SupportFragmentProcessorUnit());
processorUnits.add(new NativeFragmentProcessorUnit());
Safe Call (?. ?:)
先看这一段懵逼的代码1
2//ADD_WITH_CHECK_BODY_MAP是一个HashMap
ADD_WITH_CHECK_BODY_MAP[needsPermissionParameter]?.addHasSelfPermissionsCondition(builder, activityVar, permissionField) ?: builder.beginControlFlow("if (\$T.hasSelfPermissions(\$N, \$N))", PERMISSION_UTILS, activityVar, permissionField)
用Java理解是啥样子
1 | SensitivePermissionInterface anInterface = ADD_WITH_CHECK_BODY_MAP.get(needsPermissionParameter); |