Is there an easier alternative to mimicking the splat operator?

本小妞迷上赌 提交于 2019-12-05 04:47:31

It depends on your definition of simpler, but you could write a class utilizing the Builder pattern:

public class MyProcessBuilder {
    List<String> args;

    MyProcessBuilder( String text, String location ) {
        args = new ArrayList<String>();
        args.add( text );
        args.add( location );
    }

    MyProcessBuilder arg( String arg ) {
        args.add( arg );
        return this;
    }

    MyProcessBuilder args( String... args ) {
        this.args.addAll( Arrays.asList( args ) );
        return this;
    }

    public ProcessBuilder go() {
        return new ProcessBuilder( args );
    }

    public static MyProcessBuilder callScript( String location ) {
        return new MyProcessBuilder( "something", location );
    }

    public static void main( String[] args ) {
        callScript( "/tmp/bla" ).arg( "something else" ).arg( "more" ).go();
    }
}

Write a utility splat() and publish it?:)

This might look more uniform:

List<String> finalArgs = new ArrayList<String>();

finalArgs.addAll(Arrays.asList( "something" ));
finalArgs.addAll(Arrays.asList( scriptLocation ));
finalArgs.addAll(Arrays.asList( extraArgs )));

ProcessBuilder pb = new ProcessBuilder(finalArgs);

When you call

ProcessBuilder pb = new ProcessBuilder("something", scriptLocation, /* extraArgs */);

If you have

public ProcessBuilder(String something, String scriptLocation, String... extraArgs);

Then you can call this method in many ways:

ProcessBuilder pb = new ProcessBuilder("something", "/tmp/script.sh");

ProcessBuilder pb = new ProcessBuilder("something", "/tmp/script.sh","someArg");

ProcessBuilder pb = new ProcessBuilder("something", "/tmp/script.sh","someArg","someArg2");



ProcessBuilder pb = new ProcessBuilder("something", "/tmp/script.sh");

ProcessBuilder pb = new ProcessBuilder("something", "/tmp/script.sh",new String[]{});

ProcessBuilder pb = new ProcessBuilder("something", "/tmp/script.sh",new String[]{"someArg"});

ProcessBuilder pb = new ProcessBuilder("something", "/tmp/script.sh",new String[]{"someArg","someArg2"});



ArrayList<String> someStringList = new ArrayList<String>();
someStringList .add("SomeArg");
someStringList .add("SomeArg2");
String[] extraArgs = someStringList .toArray(new String[someStringList .size()]);
ProcessBuilder pb = new ProcessBuilder("something", "/tmp/script.sh",extraArgs);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!