ex1gtnim7d
V2EX  ›  Android

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

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

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

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

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

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

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