첫째, 우리는 주석을 정의 -
는
@AsyncTask
void doSomething(int a){
Log.d("here");
}
여러분의 도움에 감사드립니다 방법 :
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
public class AsyncTaskHandler {
@SuppressWarnings("unchecked")
public static <T> T handle(T origin) {
// collect async methods
List<Method> asyncMethods = Arrays.stream(origin.getClass().getMethods())
.filter(m -> m.getAnnotation(AsyncTask.class) != null)
.collect(Collectors.toList());
// if no async method, return itself
if (asyncMethods.isEmpty()) {
return origin;
}
return (T) Enhancer.create(origin.getClass(), (MethodInterceptor) (obj, method, args, proxy) -> {
// if asyn, wrapped in your async code, here I simply create a new thread
if (asyncMethods.contains(method)) {
// your async logic
new Thread(() -> {
try {
proxy.invoke(origin, args);
} catch (Throwable e) {
e.printStackTrace();
}
}).start();
return null;
}
return proxy.invoke(origin, args);
});
}
}
코드를 테스트 해 봅시다.
public class SomeObject {
public static void main(String[] args) {
SomeObject so = SomeObject.create();
so.syncDo("1");
so.asyncDo("2");
so.syncDo("3");
so.asyncDo("4");
}
public static SomeObject create() {
return AsyncTaskHandler.handle(new SomeObject());
}
protected SomeObject() {}
@AsyncTask
public void asyncDo(String who) {
System.out.println(who + "\tThread: " + Thread.currentThread());
}
public void syncDo(String who) {
System.out.println(who + "\tThread: " + Thread.currentThread());
}
}
출력
은 다음과 같습니다
1 Thread: Thread[main,5,main]
3 Thread: Thread[main,5,main]
2 Thread: Thread[Thread-0,5,main]
5 Thread: Thread[Thread-1,5,main]
수정 클래스가 위험 모든 JVM의 유지가 필요합니다. 생성 된 클래스를 생성하거나 프록시를 사용하는 것이 어떻습니까? –