在我阅读春季教程时,我发现了类似的内容:
LocalChangeInterceptor localChangeInterceptor;
localChangeInterceptor = new LocalChangeInterceptor();
那么这种方式有什么不同?
LocalChangeInterceptor localChangeInterceptor = new LocalChangeInterceptor();
另外,我想知道为什么人们喜欢
if (String.class.equals(sourceType.getType()))
到
if (sourceType.getType().equals(String.class))
答案 0 :(得分:2)
在此:
LocalChangeInterceptor localChangeInterceptor;
localChangeInterceptor = new LocalChangeInterceptor();
您要做的是首先创建对LocalChangeInterceptor
的引用,然后在第二行创建一个新对象并将其引用传递给您的变量。
在第二个中,你只需一步即可。您创建引用并立即将值传递给它。
LocalChangeInterceptor localChangeInterceptor = new LocalChangeInterceptor();
这:if (String.class.equals(sourceType.getType()))
与以下内容相同:
if (sourceType.getType().equals(String.class))
另外,我想给你一个提示。 Stackoverflow不适合自学编程。这个问题就是例如。如果您再搜索一下,您可以自己回答。我强烈建议您需要付出更多努力。自学编程不是一件容易的事。
祝你好运。
答案 1 :(得分:2)
LocalChangeInterceptor localChangeInterceptor = new LocalChangeInterceptor();
与
相同LocalChangeInterceptor localChangeInterceptor;
localChangeInterceptor = new LocalChangeInterceptor();
但是,您有时必须拆分作业以扩展参考的范围。例如,在打开数据库Connection
时,您将拆分声明,以便在connection
块中提供finally
引用。
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
}
}
使用
if (String.class.equals(sourceType.getType()))
如果NullPointerExcpetion
返回getType()
,则会避免null
。
那是因为当您将代码翻转到
时if (sourceType.getType().equals(String.class)) {
在运行时它尝试执行
if (**null**.equals(String.class)) { // NPE!
答案 2 :(得分:1)
@TheCrafter先前的答案回答了你的第一部分问题。
但是,为什么人们更喜欢
if (String.class.equals(sourceType.getType()))
到
if (sourceType.getType().equals(String.class))
如果因为第二个变量可以抛出NullPointerException。
最好将equals
方法调用为永远不会为null
的已知常量值。 String.class
符合这一点。
答案 3 :(得分:0)
对于您的第一个问题,唯一的区别是变量在声明后初始化。这在某些情况下很有用,其中变量暂时不会使用,因此在使用之前不需要包含任何数据。查看延迟初始化。
对于第二个,想法是来阻止NullPointerException
。如果sourceType.getType()
返回null
,则第二个示例会抛出一个NPE,,因为我们试图从引用null 的变量中调用equals
。但是在第一个例子中,我们正在调用equals
一些我们知道不会为空的东西。如果第一个示例中sourceType.getType()
为null,则equals
将返回false而不是抛出NPE。将null
传递给equals方法将返回false
答案 4 :(得分:0)
因为sourceType.getType()
可能返回null而String.class
总是返回class java.lang.String
。
那么?什么错了?
好吧,如果在结果返回null值后翻译它,则可以阅读以下代码
if (sourceType.getType().equals(String.class))
变得像这样
if (null.equals(String.class))
并且您的代码将以NullPointerException
错误结束。
答案 5 :(得分:0)
这两个陈述之间没有功能差异。
LocalChangeInterceptor localChangeInterceptor = new LocalChangeInterceptor();
LocalChangeInterceptor localChangeInterceptor;
localChangeInterceptor = new LocalChangeInterceptor();
在它们之间进行选择主要是风格的,如果你试图阻止过长的线条,通常只会产生影响。
不同的平等检查之间存在微妙但重要的区别。
String.class.equals(sourceType.getType())`
`sourceType.getType().equals(String.class)`
在一个重要的案例中表现得非常不同,但(正如TheCrafter所提到的)你应该能够通过一点努力自己找出答案。
如果您遇到问题,请考虑sourceType
的可能值,以及这可能会如何影响该语句的两个版本的行为。