出于某种原因,我需要将groovy代码重写为java。如果重要的话,它是 gradle 插件。但我不明白一些代码。您能一步步解释一下吗?可能用java代码吗?
class DeployPlugin implements Plugin<Project> {
@Override
void apply(Project project) {
project.with {
apply plugin: 'org.hidetake.ssh'
ssh.settings {
identity = file(ssh_file)
knownHosts = allowAnyHosts
passphrase = ssh_passphrase
}
...
据我了解 project.with{ }
意味着内部的方法(哪个?)被 project
实例调用。
apply plugin: 'org.hidetake.ssh'
- 可以用 project.getPlugins() .apply("org.hidetake.ssh")
表示吗?
ssh.settings
- 这里的ssh
是什么?如果它是一个变量,我怎样才能在java中获取它的实例?
ssh.settings {someExpressions}
- 在此上下文中花括号的用途是什么?
最佳答案
Java 中的代码可能如下所示:
public class DeployPlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
project.getPlugins().apply("org.hidetake.ssh");
org.hidetake.groovy.ssh.core.Service ssh = project.getExtensions().getByType(org.hidetake.groovy.ssh.core.Service.class);
ssh.settings(new MethodClosure(this, "configureSettingsClosure"));
}
private void configureSettingsClosure(org.hidetake.groovy.ssh.core.settings.GlobalSettings settings) {
settings.setIdentity(ssh_file);
settings.setKnownHosts(settings.getAllowAnyHosts());
settings.setPassphrase("p@ssw0rd");
}
或者如果你不想依赖 groovy-ssh
可能是这样的,但我不推荐它:
public class DeployPlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
project.getPlugins().apply("org.hidetake.ssh");
Object ssh = project.getExtensions().getByName("ssh");
try {
Method settings = ssh.getClass().getDeclaredMethod("settings", Closure.class);
settings.invoke(ssh, new MethodClosure(this, "configureSettingsClosure"));
} catch (IllegalAccessException | NoSuchMethodException e) {
throw new AssertionError("Should not happen except by using a different groovy-ssh version that changed incompatibly", e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private void configureSettingsClosure(Object settings) throws InvocationTargetException {
try {
Method setIdentity = settings.getClass().getDeclaredMethod("setIdentity", Object.class);
setIdentity.invoke(settings, ssh_file);
Method getAllowAnyHosts = settings.getClass().getDeclaredMethod("getAllowAnyHosts");
Method setKnownHosts = settings.getClass().getDeclaredMethod("setKnownHosts", File.class);
setKnownHosts.invoke(settings, getAllowAnyHosts.invoke(settings));
Method setPassphrase = settings.getClass().getDeclaredMethod("setPassphrase", String.class);
setPassphrase.invoke(settings, "p@ssw0rd");
} catch (NoSuchMethodException | IllegalAccessException e) {
throw new AssertionError("Should not happen except by using a different groovy-ssh version that changed incompatibly", e);
}
}
关于java - 理解java中的一些groovy代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43887293/