如何为方面类中的拦截对象实例提供唯一标识符?我们已经定义了一个跟踪接口,该接口应该为每个被拦截的对象提供唯一的ID,但是在运行该跟踪接口时,它会引发类强制转换异常,就像该接口没有被编织到被拦截的对象上一样。
这是呼叫代码
val urlConnection: HttpURLConnection
val result: String?
try {
//Connect
urlConnection = URL("http://www.google.com").openConnection() as HttpURLConnection
urlConnection.requestMethod = "POST"
urlConnection.connectTimeout = 10000
urlConnection.connect()
//Write
val outputStream = urlConnection.outputStream
val writer = BufferedWriter(OutputStreamWriter(outputStream, "UTF-8"))
writer.write("data")
writer.close()
outputStream.close()
val responseCode = urlConnection.responseCode
if (responseCode == HttpsURLConnection.HTTP_OK) {
//Read
val bufferedReader = BufferedReader(InputStreamReader(urlConnection.inputStream, "UTF-8"))
var line: String?
val sb = StringBuilder()
while (bufferedReader.readLine() != null) {
line = bufferedReader.readLine()
sb.append(line)
}
bufferedReader.close()
result = sb.toString()
} else {
result = "response : $responseCode"
}
Log.e(this.javaClass.simpleName, result)
} catch (e: UnsupportedEncodingException) {
e.printStackTrace()
} catch (e: JSONException) {
e.printStackTrace()
} catch (e: ProtocolException) {
e.printStackTrace()
} catch (e: MalformedURLException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
这是方面类
@Pointcut("call(* java.net.URL.openConnection())")
public void getUrlOpenConnectionPointCut() {
}
@AfterReturning(pointcut = "getUrlOpenConnectionPointCut()", returning = "connection")
public void afterActivityCreated(JoinPoint joinPoint, HttpURLConnection connection) throws Exception {
TrackInterface tracInt = (TrackInterface)connection;
tracInt.setTrackId();
}
@DeclareMixin("java.net.HttpURLConnection")
public static TrackInterface addTrackingIdentifier() {
return new TrackInterfaceImpl();
}
public interface TrackInterface {
void setTrackId();
int getTrackId();
}
static class TrackInterfaceImpl implements TrackInterface {
int trackId;
@Override
public void setTrackId() {
trackId = new Random(Integer.MAX_VALUE).nextInt();
}
@Override
public int getTrackId() {
return trackId;
}
}