EventBus是一款針對Android優化的發佈/訂閱事件總線。主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,線程之間傳遞消息.優勢是開銷小,代碼更優雅。以及將發送者和接收者解耦。緩存
//經過反射,獲取到訂閱者的全部方法
Method[] methods = clazz.getMethods();
for (Method method : methods) { String methodName = method.getName(); //只找以onEvent開頭的方法 if (methodName.startsWith(eventMethodName)) { int modifiers = method.getModifiers(); //判斷訂閱者是不是public的,而且是否有修飾符,看來訂閱者只能是public的,而且不能被final,static等修飾 if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) { //得到訂閱函數的參數 Class<?>[] parameterTypes = method.getParameterTypes(); //看了參數的個數只能是1個 if (parameterTypes.length == 1) { //獲取onEvent後面的部分 String modifierString = methodName.substring(eventMethodName.length()); ThreadMode threadMode; if (modifierString.length() == 0) { //訂閱函數爲onEvnet //記錄線程模型爲PostThread,意義就是發佈事件和接收事件在同一個線程執行,詳細能夠參考我對於四個訂閱函數不一樣點分析 threadMode = ThreadMode.PostThread; } else if (modifierString.equals("MainThread")) { //對應onEventMainThread threadMode = ThreadMode.MainThread; } else if (modifierString.equals("BackgroundThread")) { //對應onEventBackgrondThread threadMode = ThreadMode.BackgroundThread; } else if (modifierString.equals("Async")) { //對應onEventAsync threadMode = ThreadMode.Async; } else { if (skipMethodVerificationForClasses.containsKey(clazz)) { continue; } else { throw new EventBusException("Illegal onEvent method, check for typos: " + method); } } //獲取參數類型,其實就是接收事件的類型 Class<?> eventType = parameterTypes[0]; methodKeyBuilder.setLength(0); methodKeyBuilder.append(methodName); methodKeyBuilder.append('>').append(eventType.getName()); String methodKey = methodKeyBuilder.toString(); if (eventTypesFound.add(methodKey)) { // Only add if not already found in a sub class //封裝一個訂閱方法對象,這個對象包含Method對象,threadMode對象,eventType對象 subscriberMethods.add(new SubscriberMethod(method, threadMode, eventType)); } } } else if (!skipMethodVerificationForClasses.containsKey(clazz)) { Log.d(EventBus.TAG, "Skipping method (not public, static or abstract): " + clazz + "." + methodName); } } } //看了還會遍歷父類的訂閱函數 clazz = clazz.getSuperclass(); } //最後加入緩存,第二次使用直接從緩存拿 if (subscriberMethods.isEmpty()) { throw new EventBusException("Subscriber " + subscriberClass + " has no public methods called " + eventMethodName); } else { synchronized (methodCache) { methodCache.put(key, subscriberMethods); } return subscriberMethods; } }