2024-04-20 09:00:01

Java的隐藏特性

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


当前回答

一些控制流的技巧,最后围绕一个return语句:

int getCount() { 
  try { return 1; }
  finally { System.out.println("Bye!"); }
}

确定赋值规则将检查最终变量总是通过简单的控制流分析进行赋值:

final int foo;
if(...)
  foo = 1;
else
  throw new Exception();
foo+1;

其他回答

您可以使用Class<T>对象添加泛型类型的运行时检查,当在某个配置文件中创建类且无法为类的泛型类型添加编译时检查时,这非常方便。你不希望类在运行时爆炸,如果应用程序碰巧配置错误,你不希望所有的类都充满了检查的实例。

public interface SomeInterface {
  void doSomething(Object o);
}
public abstract class RuntimeCheckingTemplate<T> {
  private Class<T> clazz;
  protected RuntimeChecking(Class<T> clazz) {
    this.clazz = clazz;
  }

  public void doSomething(Object o) {
    if (clazz.isInstance(o)) {
      doSomethingWithGeneric(clazz.cast(o));
    } else {
      // log it, do something by default, throw an exception, etc.
    }
  }

  protected abstract void doSomethingWithGeneric(T t);
}

public class ClassThatWorksWithStrings extends RuntimeCheckingTemplate<String> {
  public ClassThatWorksWithStrings() {
     super(String.class);
  }

  protected abstract void doSomethingWithGeneric(T t) {
    // Do something with the generic and know that a runtime exception won't occur 
    // because of a wrong type
  }
}

最终初始化可以推迟。

它确保即使使用复杂的逻辑流也始终设置返回值。很容易错过一个case并意外返回null。它并不是不可能返回null,只是很明显它是故意的:

public Object getElementAt(int index) {
    final Object element;
    if (index == 0) {
         element = "Result 1";
    } else if (index == 1) {
         element = "Result 2";
    } else {
         element = "Result 3";
    }
    return element;
}

这并不是一个真正的功能,而是我最近在一些网页上发现的一个有趣的技巧:

class Example
{
  public static void main(String[] args)
  {
    System.out.println("Hello World!");
    http://Phi.Lho.free.fr

    System.exit(0);
  }
}

是一个有效的Java程序(尽管它会生成警告)。 如果你不明白为什么,请看格雷戈里的回答!;-)好吧,这里的语法高亮也给了一个提示!

前几天我对实例初始化器感到惊讶。我删除了一些代码折叠方法,最终创建了多个实例初始化器:

public class App {
    public App(String name) { System.out.println(name + "'s constructor called"); }

    static { System.out.println("static initializer called"); }

    { System.out.println("instance initializer called"); }

    static { System.out.println("static initializer2 called"); }

    { System.out.println("instance initializer2 called"); }

    public static void main( String[] args ) {
        new App("one");
        new App("two");
  }
}

执行main方法将显示:

static initializer called
static initializer2 called
instance initializer called
instance initializer2 called
one's constructor called
instance initializer called
instance initializer2 called
two's constructor called

我想,如果您有多个构造函数并且需要通用代码,那么这些将很有用

它们还提供了初始化类的语法糖:

List<Integer> numbers = new ArrayList<Integer>(){{ add(1); add(2); }};

Map<String,String> codes = new HashMap<String,String>(){{ 
  put("1","one"); 
  put("2","two");
}};

你可以在方法中声明一个类:

public Foo foo(String in) {
    class FooFormat extends Format {
        public Object parse(String s, ParsePosition pp) { // parse stuff }
    }
    return (Foo) new FooFormat().parse(in);

}