2024-04-20 09:00:01

Java的隐藏特性

在阅读了c#的隐藏特性之后,我想知道Java的隐藏特性有哪些?


当前回答

因为还没有人说过(我认为)我最喜欢的功能是自动装箱!

public class Example
{
    public static void main(String[] Args)
    {
         int a = 5;
         Integer b = a; // Box!
         System.out.println("A : " + a);
         System.out.println("B : " + b);
    }
}

其他回答

它并不是完全隐藏的,但反射是非常有用和强大的。使用简单的class . forname("…"). newinstance()是很好的,其中类类型是可配置的。编写这种工厂实现很容易。

我喜欢方法的静态导入。

例如,创建以下util类:

package package.name;

public class util {

     private static void doStuff1(){
        //the end
     }

     private static String doStuff2(){
        return "the end";
     }

}

然后像这样使用它。

import static package.name.util.*;

public class main{

     public static void main(String[] args){
          doStuff1(); // wee no more typing util.doStuff1()
          System.out.print(doStuff2()); // or util.doStuff2()
     }

}

静态导入适用于任何类,甚至数学…

import static java.lang.Math.*;
import static java.lang.System.out;
public class HelloWorld {
    public static void main(String[] args) {
        out.println("Hello World!");
        out.println("Considering a circle with a diameter of 5 cm, it has:");
        out.println("A circumference of " + (PI * 5) + "cm");
        out.println("And an area of " + (PI * pow(5,2)) + "sq. cm");
    }
}

同一个类的实例可以访问其他实例的私有成员:

class Thing {
  private int x;

  public int addThings(Thing t2) {
    return this.x + t2.x;  // Can access t2's private value!
  }
}

源代码url。例如,这是一些合法的java源代码:

http://google.com

(是的,这是在Java Puzzlers中。我笑了…)

一种可以为基于Java控制台的应用程序显示启动画面的功能。

使用带有-splash选项的命令行工具java或javaw

eg:

java -splash:C:\myfolder\myimage.png -classpath myjarfile.jar com.my.package.MyClass

C:\myfolder\myimage.png的内容将显示在你的屏幕中央,每当你执行类"com.my.package.MyClass"