gpt4 book ai didi

Java : the method to instantiate an object

转载 作者:行者123 更新时间:2023-12-01 16:59:05 27 4
gpt4 key购买 nike

当我阅读 spring 教程时,我发现了这样的内容:

LocalChangeInterceptor localChangeInterceptor;
localChangeInterceptor = new LocalChangeInterceptor();

那么这种方式有什么区别呢?

LocalChangeInterceptor localChangeInterceptor = new LocalChangeInterceptor();

另外,我想知道为什么人们更喜欢

if (String.class.equals(sourceType.getType()))    

if (sourceType.getType().equals(String.class))

最佳答案

  1. LocalChangeInterceptor localChangeInterceptor = new LocalChangeInterceptor();

    实际上

    相同
    LocalChangeInterceptor localChangeInterceptor;
    localChangeInterceptor = new LocalChangeInterceptor();

    但是,有时您必须拆分作业才能扩展引用的范围。例如,在打开数据库 Connection 时,您可以拆分声明,以便 connection 引用在 finally block 中可用。

    Connection connection;
    try {
    connection = DriverManager.getConnection(...);
    // Do statement stuff that may throw exceptions
    } catch (SQLException e) {
    // Handle exception
    } finally {
    // Close connection
    if (connection != null) { // Available inside finally,
    connection.close(); // because declared outside the try block
    }
    }
  2. if (String.class.equals(sourceType.getType()))

    如果 getType() 返回 null,则可以避免 NullPointerExcpetion

    那是因为当你将代码翻转到

    if (sourceType.getType().equals(String.class)) {

    运行时它尝试执行

    if (**null**.equals(String.class)) { // NPE!

关于Java : the method to instantiate an object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29129029/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com