函数体作为方法调用的参数
Function body as arguments to a method call
我正在阅读一些创建连接并发送 SOAP 消息的程序。我遇到了一个奇怪的语句,其中在方法参数中传递了一个包含主体的完整函数。任何人都可以解释一下吗?请注意,这是一个工作代码。
//Open up connection
httpsConnection = (HttpsURLConnection) new URL(url).openConnection();
httpsConnection.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
这是匿名内幕class。您可以在此处阅读更多信息:http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html
Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.
假装这段代码是这样写的:
httpsConnection = (HttpsURLConnection) new URL(url).openConnection();
httpsConnection.setHostnameVerifier(new MyHostnameVerifier());
// another class file
public class MyHostnameVerifier extends HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
此代码将具有完全相同的功能。还有其他一些细微差别不适用于您的示例,但如果您有兴趣,可以在 link 中阅读它们。
我正在阅读一些创建连接并发送 SOAP 消息的程序。我遇到了一个奇怪的语句,其中在方法参数中传递了一个包含主体的完整函数。任何人都可以解释一下吗?请注意,这是一个工作代码。
//Open up connection
httpsConnection = (HttpsURLConnection) new URL(url).openConnection();
httpsConnection.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
这是匿名内幕class。您可以在此处阅读更多信息:http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html
Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.
假装这段代码是这样写的:
httpsConnection = (HttpsURLConnection) new URL(url).openConnection();
httpsConnection.setHostnameVerifier(new MyHostnameVerifier());
// another class file
public class MyHostnameVerifier extends HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
此代码将具有完全相同的功能。还有其他一些细微差别不适用于您的示例,但如果您有兴趣,可以在 link 中阅读它们。