如何为类写一个注解输出到LogCat?
How to write an annotation for classes to be outputted to LogCat?
我可以创建一个注释来进行 class 调用
Log.e("", "")
并且将方法所在的class作为第一个参数,方法名作为第二个参数?
像这样:
public class UploaderService {
@Debuggable
void onUploadProductSuccess(int productServerId) {
}
}
Logcat 输出:
UploaderService | onUploadProductSuccess 43
另外,在 Android 中使用它有什么注意事项吗?
您的问题已得到解答 here。
简而言之,是的,有点。
您可以为日志记录或任何其他目的创建自定义注释,但您必须实现一个代码来检查 类 中的注释,使用也可用于 Android 的反射。
如果这对您很重要,那么您应该创建一个代理对象来获取服务名称、方法 + 参数列表参数。
像这样:
致电:
callServiceMethod("UploaderService","onUploadProductSuccess",productServerId);
方法来源:
public void callServiceMethod(String serviceName, String methodName, Object... paramList){
Object service = ;//getting the service object by name
//getting the method
Method method = service.getClass().getMethod(methodName, paramList[0].class,...);
for ( Annotation a : m.getAnnotations() ) {
// if the annotation found then write to log
}
//in the end:
method.invoke(service , paramList[0], ...);
}
在此方法中,您可以在调用实际方法之前检查被调用服务的注释。
如您所见调用了方法并写入了日志,但是您必须调用上面的方法而不是调用 UploaderService.onUploadProductSuccess。
我可以创建一个注释来进行 class 调用
Log.e("", "")
并且将方法所在的class作为第一个参数,方法名作为第二个参数?
像这样:
public class UploaderService {
@Debuggable
void onUploadProductSuccess(int productServerId) {
}
}
Logcat 输出:
UploaderService | onUploadProductSuccess 43
另外,在 Android 中使用它有什么注意事项吗?
您的问题已得到解答 here。 简而言之,是的,有点。 您可以为日志记录或任何其他目的创建自定义注释,但您必须实现一个代码来检查 类 中的注释,使用也可用于 Android 的反射。
如果这对您很重要,那么您应该创建一个代理对象来获取服务名称、方法 + 参数列表参数。
像这样:
致电:
callServiceMethod("UploaderService","onUploadProductSuccess",productServerId);
方法来源:
public void callServiceMethod(String serviceName, String methodName, Object... paramList){
Object service = ;//getting the service object by name
//getting the method
Method method = service.getClass().getMethod(methodName, paramList[0].class,...);
for ( Annotation a : m.getAnnotations() ) {
// if the annotation found then write to log
}
//in the end:
method.invoke(service , paramList[0], ...);
}
在此方法中,您可以在调用实际方法之前检查被调用服务的注释。
如您所见调用了方法并写入了日志,但是您必须调用上面的方法而不是调用 UploaderService.onUploadProductSuccess。