一图抵千言《ARouter简明扼要原理分析》

配置

kotlin项目:

module App:

代码语言:javascript代码运行次数:0运行复制

apply plugin: 'kotlin-kapt'defaultConfig{ javaCompileOptions {   annotationProcessorOptions {   //AROUTER_MODULE_NAME必配项 用于拼接生成文件名 AROUTER_GENERATE_DOC    // AROUTER_GENERATE_DOC = enable 生成Json文档   // 生成的文档路径 : build/generated/source/apt/(debug or release)/com/alibaba/android/arouter/docs/arouter-map-of-${moduleName}.json   arguments = [AROUTER_MODULE_NAME:project_name,AROUTER_GENERATE_DOC:"enable"]     }   }}dependencies{  api 'com.alibaba:arouter-api:1.5.0'  kapt 'com.alibaba:arouter-compiler:1.2.2'}

代码语言:javascript代码运行次数:0运行复制

//项目根目录build.gradledependencies {  classpath "com.alibaba:arouter-register:1.0.2"}

源码流程分析

三个关键阶段

一图抵千言《ARouter简明扼要原理分析》

ARouter源码分析.png

自定义处理器工作流程:

一图抵千言《ARouter简明扼要原理分析》

整体流程.png

自定义处理器源码分析:结构图

一图抵千言《ARouter简明扼要原理分析》

ARoute注解源码解析-1.png

生成类的关系

调用类:

代码语言:javascript代码运行次数:0运行复制

@Route(path = "/kotlin/test")class KotlinTestActivity : Activity() {    @Autowired    @JvmField var name: String? = null    @Autowired    @JvmField var age: Int? = 0    override fun onCreate(savedInstanceState: Bundle?) {        ARouter.getInstance().inject(this)  // Start auto inject.        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_kotlin_test)        content.text = "name = $name, age = $age"    }}

ARouter生成类:

代码语言:javascript代码运行次数:0运行复制

public class KotlinTestActivity$$ARouter$$Autowired implements ISyringe {  private SerializationService serializationService;  @Override  public void inject(Object target) {    serializationService = ARouter.getInstance().navigation(SerializationService.class);    KotlinTestActivity substitute = (KotlinTestActivity)target;    substitute.name = substitute.getIntent().getExtras() == null ? substitute.name : substitute.getIntent().getExtras().getString("name", substitute.name);    substitute.age = substitute.getIntent().getIntExtra("age", substitute.age);  }}

这段代码最终会利用当前类名和规则,拼接成KotlinTestActivity$$ARouter$$Autowired的全类名,然后利用反射传进对象。然后执行inject(this); 然后里面会初始化传输字段序列化服务,然后强转target,开始赋值数据

生成类文件的关系

一图抵千言《ARouter简明扼要原理分析》

RouteProcessor生成文件.png

由此可总结出下面整体工作流程

ARouter整体工作流程

一图抵千言《ARouter简明扼要原理分析》

整体工作流程.png

运行时原理分析初始化工作流程分析代码语言:javascript代码运行次数:0运行复制

  //初始化  ARouter.init(getApplication());    _ARouter.init(application)     LogisticsCenter.init(mContext, executor)  

LogisticsCenter.init(mContext, executor):

代码语言:javascript代码运行次数:0运行复制

public synchronized static void init(Context context, ThreadPoolExecutor tpe) throws HandlerException {        mContext = context;        executor = tpe;        try {            long startInit = System.currentTimeMillis();            //load by plugin first            loadRouterMap();            if (registerByPlugin) {                logger.info(TAG, "Load router map by arouter-auto-register plugin.");            } else {                //1 生成文件所有文件的全类名字符串集合                Set routerMap;                // It will rebuild router map every times when debuggable.                if (ARouter.debuggable() || PackageUtils.isNewVersion(context)) {                    logger.info(TAG, "Run with debug mode or new install, rebuild router map.");                    // These class was generated by arouter-compiler.                    //2. 赋值集合                    routerMap = ClassUtils.getFileNameByPackageName(mContext, ROUTE_ROOT_PAKCAGE);                    if (!routerMap.isEmpty()) {                        context.getSharedPreferences(AROUTER_SP_CACHE_KEY, Context.MODE_PRIVATE).edit().putStringSet(AROUTER_SP_KEY_MAP, routerMap).apply();                    }                    PackageUtils.updateVersion(context);    // Save new version name when router map update finishes.                } else {                    logger.info(TAG, "Load router map from cache.");                    routerMap = new HashSet(context.getSharedPreferences(AROUTER_SP_CACHE_KEY, Context.MODE_PRIVATE).getStringSet(AROUTER_SP_KEY_MAP, new HashSet()));                }                logger.info(TAG, "Find router map finished, map size = " + routerMap.size() + ", cost " + (System.currentTimeMillis() - startInit) + " ms.");                startInit = System.currentTimeMillis();                 //3. 遍历集合                for (String className : routerMap) {                // 这里装在了3中类别的文件: (1) Root文件                    if (className.startsWith(ROUTE_ROOT_PAKCAGE + DOT + SDK_NAME + SEPARATOR + SUFFIX_ROOT)) {                        // This one of root elements, load root.                        ((IRouteRoot) (Class.forName(className).getConstructor().newInstance())).loadInto(Warehouse.groupsIndex);                        //(2) Interceptor 文件                    } else if (className.startsWith(ROUTE_ROOT_PAKCAGE + DOT + SDK_NAME + SEPARATOR + SUFFIX_INTERCEPTORS)) {                        // Load interceptorMeta                        ((IInterceptorGroup) (Class.forName(className).getConstructor().newInstance())).loadInto(Warehouse.interceptorsIndex);                         // //(3) Provider 文件                      } else if (className.startsWith(ROUTE_ROOT_PAKCAGE + DOT + SDK_NAME + SEPARATOR + SUFFIX_PROVIDERS)) {                        // Load providerIndex                        ((IProviderGroup) (Class.forName(className).getConstructor().newInstance())).loadInto(Warehouse.providersIndex);                    }                }            }            logger.info(TAG, "Load root element finished, cost " + (System.currentTimeMillis() - startInit) + " ms.");            if (Warehouse.groupsIndex.size() == 0) {                logger.error(TAG, "No mapping files were found, check your configuration please!");            }            if (ARouter.debuggable()) {                logger.debug(TAG, String.format(Locale.getDefault(), "LogisticsCenter has already been loaded, GroupIndex[%d], InterceptorIndex[%d], ProviderIndex[%d]", Warehouse.groupsIndex.size(), Warehouse.interceptorsIndex.size(), Warehouse.providersIndex.size()));            }        } catch (Exception e) {            throw new HandlerException(TAG + "ARouter init logistics center exception! [" + e.getMessage() + "]");        }    }

可以看出没加载AutoWired文件,也就是说@AutoWired注解字段 在inject()时去创建对象赋值的。 反射找到对象并将Warehouse中的结合作为参数传递进入,把信息装载到内存。注意,这里只是加载了信息,但信息里面的具体内容并未创建。什么意思呢?以Provider为例:

代码语言:javascript代码运行次数:0运行复制

public class ARouter$$Providers$$modulejava implements IProviderGroup {  @Override  public void loadInto(Map providers) {    providers.put("com.alibaba.android.arouter.demo.service.HelloService", RouteMeta.build(RouteType.PROVIDER, HelloServiceImpl.class, "/yourservicegroupname/hello", "yourservicegroupname", null, -1, -2147483648));    providers.put("com.alibaba.android.arouter.facade.service.SerializationService", RouteMeta.build(RouteType.PROVIDER, JsonServiceImpl.class, "/yourservicegroupname/json", "yourservicegroupname", null, -1, -2147483648));    providers.put("com.alibaba.android.arouter.demo.module1.testservice.SingleService", RouteMeta.build(RouteType.PROVIDER, SingleService.class, "/yourservicegroupname/single", "yourservicegroupname", null, -1, -2147483648));  }}

反射生成ARouter$$Providers$$modulejava对象,但我们用的是com.alibaba.android.arouter.demo.service.HelloServiceHelloService这个具体类。但这个类这是并未实例化,只有用到的时候才回去实例化创建。其他同理。

LogisticsCenter.init(mContext, executor): 还用到两个重要的类和方法: ClassUtils/Warehouse 1. ClassUtils.getFileNameByPackageName(mContext, ROUTE_ROOT_PAKCAGE);

代码语言:javascript代码运行次数:0运行复制

public static Set getFileNameByPackageName(Context context, final String packageName) throws PackageManager.NameNotFoundException, IOException, InterruptedException {        final Set classNames = new HashSet();        List paths = getSourcePaths(context);        //线程同步        final CountDownLatch parserCtl = new CountDownLatch(paths.size());        for (final String path : paths) {            DefaultPoolExecutor.getInstance().execute(new Runnable() {                @Override                public void run() {                //Dex文件                    DexFile dexfile = null;                    try {                        if (path.endsWith(EXTRACTED_SUFFIX)) {                            //NOT use new DexFile(path), because it will throw "permission error in /data/dalvik-cache"                            dexfile = DexFile.loadDex(path, path + ".tmp", 0);                        } else {                            dexfile = new DexFile(path);                        }                        Enumeration dexEntries = dexfile.entries();                        while (dexEntries.hasMoreElements()) {                            String className = dexEntries.nextElement();                            //核心判断 packageName是我们上面传入的参数ROUTE_ROOT_PAKCAGE = "com.alibaba.android.arouter.routes"                            if (className.startsWith(packageName)) {                                classNames.add(className);                            }                        }                    } catch (Throwable ignore) {                        Log.e("ARouter", "Scan map file in dex files made error.", ignore);                    } finally {                        if (null != dexfile) {                            try {                                dexfile.close();                            } catch (Throwable ignore) {                            }                        }                        //也就是说,如果初始化加载流程没有走完,路由操作将会阻塞,知道加载流程完成                        parserCtl.countDown();                    }                }            });        }        parserCtl.await();        Log.d(Consts.TAG, "Filter " + classNames.size() + " classes by packageName ");        return classNames;    }

如果初始化加载流程没有走完,路由操作将会阻塞,直到加载流程完成

Warehouse 相当于一个加载信息装载的容器类

代码语言:javascript代码运行次数:0运行复制

class Warehouse {    // Cache route and metas      //groupsIndex 装载ARouter$$Root$$moduleName 中的Root文件      static Map<String, Class> groupsIndex = new HashMap();    //routes 按需加载完成后 把加载的数据存到routes 集合中,等项目中用到的时候,找到集合中需要的元素 再去实例化对象    static Map routes = new HashMap();    // Cache provider   //项目中用到的时候,找到集合中需要的元素 再去实例化对象     static Map providers = new HashMap();    // //每个服务的原始信息加载完成后存放到这里    static Map providersIndex = new HashMap();    // Cache interceptor       static Map<Integer, Class> interceptorsIndex = new UniqueKeyTreeMap("More than one interceptors use same priority [%s]");    static List interceptors = new ArrayList();    static void clear() {        routes.clear();        groupsIndex.clear();        providers.clear();        providersIndex.clear();        interceptors.clear();        interceptorsIndex.clear();    }}
一图抵千言《ARouter简明扼要原理分析》

整体工作流程.png

路由过程源码分析代码语言:javascript代码运行次数:0运行复制

    ARouter.getInstance()                        .build("/kotlin/test")                        .withString("name", "老王")                        .withInt("age", 23)                        .navigation();

.build("/kotlin/test") 查找分组,构建Postcard对象。

代码语言:javascript代码运行次数:0运行复制

   protected Postcard build(String path) {        if (TextUtils.isEmpty(path)) {            throw new HandlerException(Consts.TAG + "Parameter is invalid!");        } else {        // 重定向路由路径Service 如果想自定义 则实现PathReplaceService             PathReplaceService pService = ARouter.getInstance().navigation(PathReplaceService.class);            if (null != pService) {            //通过forString(path) 返回修改后的Path                path = pService.forString(path);            }            //继续往下走             return build(path, extractGroup(path), true);        }    }   

extractGroup(path):

代码语言:javascript代码运行次数:0运行复制

 private String extractGroup(String path) {        if (TextUtils.isEmpty(path) || !path.startsWith("/")) {            throw new HandlerException(Consts.TAG + "Extract the default group failed, the path must be start with '/' and contain more than 2 '/'!");        }        try {        //关键代码 defaultGroup 默认分组 以路由路径 第一个节点为分组名称            String defaultGroup = path.substring(1, path.indexOf("/", 1));            if (TextUtils.isEmpty(defaultGroup)) {                throw new HandlerException(Consts.TAG + "Extract the default group failed! There's nothing between 2 '/'!");            } else {                return defaultGroup;            }        } catch (Exception e) {            logger.warning(Consts.TAG, "Failed to extract default group! " + e.getMessage());            return null;        }    }

build(path, extractGroup(path), true);:

代码语言:javascript代码运行次数:0运行复制

  protected Postcard build(String path, String group, Boolean afterReplace) {        if (TextUtils.isEmpty(path) || TextUtils.isEmpty(group)) {            throw new HandlerException(Consts.TAG + "Parameter is invalid!");        } else {            if (!afterReplace) {                PathReplaceService pService = ARouter.getInstance().navigation(PathReplaceService.class);                if (null != pService) {                    path = pService.forString(path);                }            }            return new Postcard(path, group);        }    }

创建:Postcard对象

构建参数mBundle对象。

.navigation(); 运行在异步线程中

代码语言:javascript代码运行次数:0运行复制

 protected Object navigation(final Context context, final Postcard postcard, final int requestCode, final NavigationCallback callback) {        PretreatmentService pretreatmentService = ARouter.getInstance().navigation(PretreatmentService.class);        if (null != pretreatmentService && !pretreatmentService.onPretreatment(context, postcard)) {            // Pretreatment failed, navigation canceled.            return null;        }        // Set context to postcard.        postcard.setContext(null == context ? mContext : context);        try {        //给Postcard赋值其他数据            LogisticsCenter.completion(postcard);        } catch (NoRouteFoundException ex) {//出现异常的情况            logger.warning(Consts.TAG, ex.getMessage());            if (debuggable()) {                // Show friendly tips for user.                runInMainThread(new Runnable() {                    @Override                    public void run() {                        Toast.makeText(mContext, "There's no route matched!n" +                                " Path = [" + postcard.getPath() + "]n" +                                " Group = [" + postcard.getGroup() + "]", Toast.LENGTH_LONG).show();                    }                });            }            if (null != callback) {            // 路由回调 如果不为空                callback.onLost(postcard);            } else {                // No callback for this invoke, then we use the global degrade service.                //反射创建全局降级服务  回调 onLost方法                DegradeService degradeService = ARouter.getInstance().navigation(DegradeService.class);                if (null != degradeService) {                    degradeService.onLost(context, postcard);                }            }            return null;        }        if (null != callback) {        //回调路由成功的方法            callback.onFound(postcard);        }         //如果绿色通道为false 则添加拦截器         if (!postcard.isGreenChannel()) {   // It must be run in async thread, maybe interceptor cost too mush time made ANR.        // 运行在线程池中            interceptorService.doInterceptions(postcard, new InterceptorCallback() {                /**                 * Continue process                 *                 * @param postcard route meta                 */                @Override                public void onContinue(Postcard postcard) {                //继续处理完成后继续向下执行                     _navigation(postcard, requestCode, callback);                }                /**                 * Interrupt process, pipeline will be destory when this method called.                 *                 * @param exception Reson of interrupt.                 */                @Override                public void onInterrupt(Throwable exception) {                    if (null != callback) {                    //打断路由 停止路由                        callback.onInterrupt(postcard);                    }                    logger.info(Consts.TAG, "Navigation failed, termination by interceptor : " + exception.getMessage());                }            });        } else {         //继续处理完成后继续向下执行             return _navigation(postcard, requestCode, callback);        }        return null;    }

LogisticsCenter.completion(postcard);

代码语言:javascript代码运行次数:0运行复制

public synchronized static void completion(Postcard postcard) {        if (null == postcard) {            throw new NoRouteFoundException(TAG + "No postcard!");        }        //routes是加载信息 但为实例化对象 之前提过  所以这里第一次肯定为空        RouteMeta routeMeta = Warehouse.routes.get(postcard.getPath());        if (null == routeMeta) {            // Maybe its does't exist, or didn't load.            if (!Warehouse.groupsIndex.containsKey(postcard.getGroup())) {                throw new NoRouteFoundException(TAG + "There is no route match the path [" + postcard.getPath() + "], in group [" + postcard.getGroup() + "]");            } else {                // Load route and cache it into memory, then delete from metas.                try {                    if (ARouter.debuggable()) {                        logger.debug(TAG, String.format(Locale.getDefault(), "The group [%s] starts loading, trigger by [%s]", postcard.getGroup(), postcard.getPath()));                    }                    //对Warehouse.routes初始化 实例化分组对象 获取数据                    addRouteGroupDynamic(postcard.getGroup(), null);                    if (ARouter.debuggable()) {                        logger.debug(TAG, String.format(Locale.getDefault(), "The group [%s] has already been loaded, trigger by [%s]", postcard.getGroup(), postcard.getPath()));                    }                } catch (Exception e) {                    throw new HandlerException(TAG + "Fatal exception when loading group meta. [" + e.getMessage() + "]");                }                //重新调用自己                completion(postcard);   // Reload            }        } else {        //给postcard赋值其他信息            postcard.setDestination(routeMeta.getDestination());            postcard.setType(routeMeta.getType());            postcard.setPriority(routeMeta.getPriority());            postcard.setExtra(routeMeta.getExtra());            Uri rawUri = postcard.getUri();            if (null != rawUri) {   // Try to set params into bundle.                Map resultMap = TextUtils.splitQueryParameters(rawUri);                Map paramsType = routeMeta.getParamsType();                if (MapUtils.isNotEmpty(paramsType)) {                    // Set value by its type, just for params which annotation by @Param                    for (Map.Entry params : paramsType.entrySet()) {                        setValue(postcard,                                params.getValue(),                                params.getKey(),                                resultMap.get(params.getKey()));                    }                    // Save params name which need auto inject.                    postcard.getExtras().putStringArray(ARouter.AUTO_INJECT, paramsType.keySet().toArray(new String[]{}));                }                // Save raw uri                postcard.withString(ARouter.RAW_URI, rawUri.toString());            }             //类型判断 PROVIDER类型实例化对象 PROVIDER/FRAGMENT默认开启通道,不经过拦截            switch (routeMeta.getType()) {                case PROVIDER:  // if the route is provider, should find its instance                    // Its provider, so it must implement IProvider                    Class providerMeta = (Class) routeMeta.getDestination();                    IProvider instance = Warehouse.providers.get(providerMeta);                    if (null == instance) { // There's no instance of this provider                        IProvider provider;                        try {                            provider = providerMeta.getConstructor().newInstance();                            provider.init(mContext);                            Warehouse.providers.put(providerMeta, provider);                            instance = provider;                        } catch (Exception e) {                            logger.error(TAG, "Init provider failed!", e);                            throw new HandlerException("Init provider failed!");                        }                    }                    postcard.setProvider(instance);                    postcard.greenChannel();    // Provider should skip all of interceptors                    break;                case FRAGMENT:                    postcard.greenChannel();    // Fragment needn't interceptors                default:                    break;            }        }    } public synchronized static void addRouteGroupDynamic(String groupName, IRouteGroup group) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {        if (Warehouse.groupsIndex.containsKey(groupName)){            // If this group is included, but it has not been loaded            // load this group first, because dynamic route has high priority.            //对Warehouse.routes初始化 实例化分组对象 获取数据            Warehouse.groupsIndex.get(groupName).getConstructor().newInstance().loadInto(Warehouse.routes);            Warehouse.groupsIndex.remove(groupName);        }        // cover old group.        if (null != group) {            group.loadInto(Warehouse.routes);        }    }

_navigation(postcard, requestCode, callback);

代码语言:javascript代码运行次数:0运行复制

  private Object _navigation(final Postcard postcard, final int requestCode, final NavigationCallback callback) {        final Context currentContext = postcard.getContext();//判断路由类型        switch (postcard.getType()) {            case ACTIVITY:                // Build intent                final Intent intent = new Intent(currentContext, postcard.getDestination());                intent.putExtras(postcard.getExtras());                // Set flags.                int flags = postcard.getFlags();                if (0 != flags) {                    intent.setFlags(flags);                }                // Non activity, need FLAG_ACTIVITY_NEW_TASK                if (!(currentContext instanceof Activity)) {                //context如果是Application 那么新建任务栈                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);                }                // Set Actions                String action = postcard.getAction();                if (!TextUtils.isEmpty(action)) {                    intent.setAction(action);                }                // Navigation in main looper.                runInMainThread(new Runnable() {                    @Override                    public void run() {                    //Activity则调用startActivity                        startActivity(requestCode, currentContext, intent, postcard, callback);                    }                });                break;            case PROVIDER:            //返回LogisticsCenter.completion(postcard)方法中创建的对象                return postcard.getProvider();            case BOARDCAST:            case CONTENT_PROVIDER:            case FRAGMENT:                Class fragmentMeta = postcard.getDestination();                try {                    Object instance = fragmentMeta.getConstructor().newInstance();                    if (instance instanceof Fragment) {                        ((Fragment) instance).setArguments(postcard.getExtras());                    } else if (instance instanceof android.support.v4.app.Fragment) {                        ((android.support.v4.app.Fragment) instance).setArguments(postcard.getExtras());                    } //反射返回fragment实例                    return instance;                } catch (Exception ex) {                    logger.error(Consts.TAG, "Fetch fragment instance error, " + TextUtils.formatStackTrace(ex.getStackTrace()));                }            case METHOD:            case SERVICE:            default:                return null;        }        return null;    }

路由结束。

一图抵千言《ARouter简明扼要原理分析》

整体工作流程(2).png

一图抵千言《ARouter简明扼要原理分析》

图片.png

以上就是一图抵千言《ARouter简明扼要原理分析》的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/18105.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
金线毛格子美甲教程
上一篇 2025年12月4日 21:46:11
淘宝退货宝运费需自付?运费怎么查?淘宝退货宝运费规则全解析:自付条件与查询指南,3步查明细避坑!
下一篇 2025年12月4日 21:47:24

相关推荐

  • Matplotlib 地图中多类型图例的创建与优化

    Matplotlib 地图中多类型图例的创建与优化Matplotlib 地图中多类型图例的创建与优化Matplotlib 地图中多类型图例的创建与优化Matplotlib 地图中多类型图例的创建与优化

    本教程旨在解决matplotlib地图可视化中,如何在一个图例中同时展示颜色块(如区域分类)和自定义标记(如特定兴趣点)的问题。文章详细介绍了当传统`patch`对象无法正确显示标记时,如何利用`matplotlib.lines.line2d`创建标记图例句柄,并将其与颜色块图例句柄合并,从而生成一…

    2026年5月10日 用户投稿
    100
  • Golang JSON序列化:控制敏感字段暴露的最佳实践

    本教程探讨golang中如何高效控制结构体字段在json序列化时的可见性。当需要将包含敏感信息的结构体数组转换为json响应时,通过利用`encoding/json`包提供的结构体标签,特别是`json:”-“`,可以轻松实现对特定字段的忽略,从而避免敏感数据泄露,确保api…

    2026年5月10日
    000
  • 比特币新手教程 比特币交易平台有哪些

    比特币是一种去中心化的数字货币,基于区块链技术实现点对点交易,具有匿名性、有限发行和不可篡改等特点;新手可通过交易所购买,P2P交易获得比特币,常用平台包括Binance、OKX和Huobi;交易流程包括注册账户、实名认证、绑定支付方式、充值法币并下单购买,可选择市价单或限价单;比特币存储方式有交易…

    2026年5月10日
    000
  • c++中的SFINAE技术是什么_c++模板编程中的SFINAE原理与应用

    SFINAE 是“替换失败不是错误”的原则,指模板实例化时若参数替换导致错误,只要存在其他合法候选,编译器不报错而是继续重载决议。它用于条件启用模板、类型检测等场景,如通过 decltype 或 enable_if 控制函数重载,实现类型特征判断。尽管 C++20 引入 Concepts 简化了部分…

    2026年5月10日
    000
  • 如何让动态追加元素的类事件生效?

    如何在追加元素后使其绑定类事件生效 在页面中引入三方 JavaScript 类并通过添加相应 class 来调用事件方法是一种常见的做法。然而,如果通过 JavaScript 追加标签元素,即使添加了对应的 class,事件也可能无法生效。 为了解决这个问题,可以尝试以下步骤: 检查追加的标签是否为…

    2026年5月10日
    000
  • Go语言mgo查询构建:深入理解bson.M与日期范围查询的正确实践

    本文旨在解决go语言mgo库中构建复杂查询时,特别是涉及嵌套`bson.m`和日期范围筛选的常见错误。我们将深入剖析`bson.m`的类型特性,解释为何直接索引`interface{}`会导致“invalid operation”错误,并提供一种推荐的、结构清晰的代码重构方案,以确保查询条件能够正确…

    2026年5月10日
    100
  • RichHandler与Rich Progress集成:解决显示冲突的教程

    在使用rich库的`richhandler`进行日志输出并同时使用`progress`组件时,可能会遇到显示错乱或溢出问题。这通常是由于为`richhandler`和`progress`分别创建了独立的`console`实例导致的。解决方案是确保日志处理器和进度条组件共享同一个`console`实例…

    2026年5月10日
    000
  • Golang goroutine与channel调试技巧

    使用go run -race检测数据竞争,结合runtime.NumGoroutine监控协程数量,通过pprof分析阻塞调用栈,利用select超时避免永久阻塞,有效排查goroutine泄漏、死锁和数据竞争问题。 Go语言的goroutine和channel是并发编程的核心,但它们也带来了调试上…

    2026年5月10日
    000
  • 使用 Jupyter Notebook 进行探索性数据分析

    Jupyter Notebook通过单元格实现代码与Markdown结合,支持数据导入(pandas)、清洗(fillna)、探索(matplotlib/seaborn可视化)、统计分析(describe/corr)和特征工程,便于记录与分享分析过程。 Jupyter Notebook 是进行探索性…

    2026年5月10日
    000
  • 《魔兽世界》将于6月11日开启国服回归技术测试

    《魔兽世界》将于6月11日开启国服回归技术测试《魔兽世界》将于6月11日开启国服回归技术测试《魔兽世界》将于6月11日开启国服回归技术测试《魔兽世界》将于6月11日开启国服回归技术测试

    《%ign%ignore_a_1%re_a_1%》官方宣布,将于6月11日开启国服回归技术测试,时间为7天,并称可以在6月内正式开服,玩家们可以访问官网下载战网客户端并预下载“巫妖王之怒”客户端,技术测试详情见下图。 WordAi WordAI是一个AI驱动的内容重写平台 53 查看详情 以上就是《…

    2026年5月10日 用户投稿
    200
  • 如何在HTML中插入表单元素_HTML表单控件与输入类型使用指南

    HTML表单通过标签构建,包含action和method属性定义数据提交目标与方式,常用input类型如text、password、email等适配不同输入需求,配合label、required、placeholder提升可用性,结合textarea、select、button等控件实现完整交互,是…

    2026年5月10日
    000
  • 创建指定大小并填充特定数据的Golang文件教程

    本文将介绍如何使用Golang创建一个指定大小的文件,并用特定数据填充它。我们将使用 `os` 包提供的函数来创建和截断文件,从而实现快速生成大文件的目的。示例代码展示了如何创建一个10MB的文件,并将其填充为全零数据。掌握这些方法,可以方便地在例如日志系统或磁盘队列等场景中,预先创建测试文件或初始…

    2026年5月10日
    000
  • Python命令怎样使用profile分析脚本性能 Python命令性能分析的基础教程

    使用Python的cProfile模块分析脚本性能最直接的方式是通过命令行执行python -m cProfile your_script.py,它会输出每个函数的调用次数、总耗时、累积耗时等关键指标,帮助定位性能瓶颈;为进一步分析,可将结果保存为文件python -m cProfile -o ou…

    2026年5月10日
    000
  • 使用 WebCodecs VideoDecoder 实现精确逐帧回退

    本文档旨在解决在使用 WebCodecs VideoDecoder 进行视频解码时,实现精确逐帧回退的问题。通过比较帧的时间戳与目标帧的时间戳,可以避免渲染中间帧,从而提高用户体验。本文将提供详细的解决方案和示例代码,帮助开发者实现精确的视频帧控制。 在使用 WebCodecs VideoDecod…

    2026年5月10日
    000
  • 如何插入查询结果数据_SQL插入Select查询结果方法

    如何插入查询结果数据_SQL插入Select查询结果方法如何插入查询结果数据_SQL插入Select查询结果方法如何插入查询结果数据_SQL插入Select查询结果方法如何插入查询结果数据_SQL插入Select查询结果方法

    使用INSERT INTO…SELECT语句可高效插入数据,通过NOT EXISTS、LEFT JOIN、MERGE语句或唯一约束避免重复;表结构不一致时可通过别名、类型转换、默认值或计算字段处理;结合存储过程可提升可维护性,支持参数化与动态SQL。 将查询结果数据插入到另一个表中,可以…

    2026年5月10日 用户投稿
    000
  • Discord.py 交互按钮超时与持久化解决方案

    本教程旨在解决Discord.py中交互按钮在一段时间后出现“This Interaction Failed”错误的问题。我们将深入探讨视图(View)的超时机制,并提供通过正确设置timeout参数以及利用bot.add_view()方法实现按钮持久化的具体方案,确保您的机器人交互功能稳定可靠,即…

    2026年5月10日
    000
  • Debian Copilot的社区活跃度如何

    debian copilot是codeberg社区维护的ai助手,旨在为debian用户提供服务。尽管搜索结果中没有直接提供关于debian copilot社区支持活跃度的具体数据,但我们可以通过debian社区的整体活跃度和特点来推断其活跃性。 Debian社区的一般情况: Debian拥有详尽的…

    2026年5月10日
    000
  • JavaScript 动态菜单点击高亮效果实现教程

    本教程详细介绍了如何使用 JavaScript 实现动态菜单的点击高亮功能。通过事件委托和状态管理,当用户点击菜单项时,被点击项会高亮显示(绿色),同时其他菜单项恢复默认样式(白色)。这种方法避免了不必要的DOM操作,提高了性能和代码可维护性,确保了无论点击方向如何,功能都能稳定运行。 动态菜单高亮…

    2026年5月10日
    200
  • c++如何实现UDP通信_c++基于UDP的网络通信示例

    UDP通信基于套接字实现,适用于实时性要求高的场景。1. 流程包括创建套接字、绑定地址(接收方)、发送(sendto)与接收(recvfrom)数据、关闭套接字;2. 服务端监听指定端口,接收客户端消息并回传;3. 客户端发送消息至服务端并接收响应;4. 跨平台需处理Winsock初始化与库链接,编…

    2026年5月10日
    000
  • html5怎么画实线_HTML5用CSS border-style:solid画元素实线边框【绘制】

    可通过CSS的border-style属性设为solid添加实线边框:一、内联样式用border:2px solid #000;二、内部样式表统一设置如div{border:1px solid #333};三、外部CSS文件定义.my-box{border:3px solid red}并引入;四、单…

    2026年5月10日
    000

发表回复

登录后才能评论
关注微信