ex1gtnim7d
V2EX  ›  Android

为什么安卓源码经常用反射不用 new?

  •  
  •   ex1gtnim7d · Oct 20, 2020 · 14808 views
    This topic created in 2092 days ago, the information mentioned may be changed or developed.

    比如 Instrument.java 类中的 Application app = (Application)clazz.newInstance();

    为什么不直接写成 Application app = new Application();

    最近阅读安卓源码发现有很多类似的写法,基本上能不 new 就不 new,这是出于什么考量呢?

    网上有人说反射是为了降低耦合,但是单纯看这个场景这行代码的话,没有看出降低耦合的地方,还是说这是反射思想用多了的一种写法习惯呢?

    codehz
        1
    codehz  
       Oct 20, 2020
    因为 clazz 是运行期传入的。。。
    TJT
        2
    TJT  
       Oct 20, 2020
    因为不能...
    billlee
        3
    billlee  
       Oct 20, 2020
    Application 是个接口或抽象类吧
    maninfog
        4
    maninfog  
       Oct 20, 2020 via Android
    试想在我们继承 Application 的情况?这样系统只能从 manifest 中拿到我们继承的类名,然后构建 Class 对象,再去实例化
    zpxshl
        5
    zpxshl  
       Oct 20, 2020 via Android
    只能反射,理由如 4 楼。
    activity 的创建过程也是同理
    lijialong1313
        6
    lijialong1313  
       Oct 20, 2020
    这其实就是 app 运行时候才知道这个是啥东西,相当于父类要先知道子信息了才能生成父类,明显只能用反射。
    fangcan
        7
    fangcan  
       Oct 21, 2020
    编码阶段无法确定的,在运行期才能确定的,只能用反射的方式实现
    hoyixi
        8
    hoyixi  
       Oct 21, 2020
    Java 日常,有配置文件的地方就有反射,因为按照配置约束,你知道用户配了个“寂寞”,但是你不知道用户写的具体是“单身狗剧荒”, 还是“单身狗 X 饥渴”
    ex1gtnim7d
        9
    ex1gtnim7d  
    OP
       Oct 21, 2020
    ```
    static public Application newApplication(Class<?> clazz, Context context)
    throws InstantiationException, IllegalAccessException,
    ClassNotFoundException {
    Application app = (Application)clazz.newInstance();
    app.attach(context);
    return app;
    }
    ```
    这个方法好像没有用到我们自己写的 Application,就是默认的 Application
    @maninfog
    @zpxshl
    ex1gtnim7d
        10
    ex1gtnim7d  
    OP
       Oct 21, 2020
    哦哦哦,我知道了,我犯糊涂了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5574 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 49ms · UTC 06:52 · PVG 14:52 · LAX 23:52 · JFK 02:52
    ♥ Do have faith in what you're doing.