String args []参数

Gap*_*oos 3 java string command-line-arguments

class MainClass
{
     public static void main(String []args)
     {
         System.out.println("B");
     }
}
Run Code Online (Sandbox Code Playgroud)

通常上述代码生成输出.如何在ABC不修改main()方法的情况下将其更改为?

Xav*_*uza 13

public class Test
{
    static 
    {
    System.out.println("ABC");
    System.exit(0);
    }

    public static void main(String []args)
    {
        System.out.println("B");
    }
}
Run Code Online (Sandbox Code Playgroud)


ass*_*ias 12

一种解决方案是隐藏System.out- 下面的代码打印ABC而不更改main:

class MainClass {

    public static void main(String[] args) {
        System.out.println("B");
    }

    static class System {
        static Printer out = new Printer();
    }
    static class Printer {
        public void println(String whatever) {
            java.lang.System.out.println("ABC");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Pet*_*rey 9

你可以做到这一点,但它是一个可怕的黑客.

import java.lang.reflect.Field;

class MainClass {
    // requires Java 7 update 5+ as the internal structure of String changed.
    static {
        try {
            Field value = String.class.getDeclaredField("value");
            value.setAccessible(true);
            value.set("B", value.get("ABC"));
        } catch (Throwable e) {
            throw new AssertionError(e);
        }
    }
    public static void main(String[] args) {
        System.out.println("B");
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @Gapchoos从技术上讲,该解决方案不会运行给定的代码.你可以运行一个不相关的类;) (3认同)