2024-04-20 09:00:01

Java的隐藏特性

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


当前回答

字符串参数化类工厂。

Class.forName( className ).newInstance();

从部署jar文件中加载资源(属性文件,xml, xslt,图像等)。

this.getClass().getClassLoader().getResourceAsStream( ... ) ;

其他回答

语言级assert关键字。

您可以使用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
  }
}

我个人很晚才发现java.lang.Void——结合泛型提高了代码的可读性,例如Callable<Void>

逗号和数组。字符串s[] = { “123”, “234”, };

您可以在枚举类的方法定义中切换(此)。当我发现这个方法真的有效时,我大声喊了一声“什么!”