在阅读了c#的隐藏特性之后,我想知道Java的隐藏特性有哪些?
当前回答
您可以使用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
}
}
其他回答
同一个类的实例可以访问其他实例的私有成员:
class Thing {
private int x;
public int addThings(Thing t2) {
return this.x + t2.x; // Can access t2's private value!
}
}
我喜欢方法的静态导入。
例如,创建以下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 . forname("…"). newinstance()是很好的,其中类类型是可配置的。编写这种工厂实现很容易。
我可以添加扫描仪对象。它是解析的最佳选择。
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();
Self-bound泛型:
class SelfBounded<T extends SelfBounded<T>> {
}
http://www.artima.com/weblogs/viewpost.jsp?thread=136394
推荐文章
- 在Selenium中等待页面加载
- Maven父pom vs模块pom
- 将JSON数据转换为Java对象
- Java的隐藏特性
- 使用Java 8的可选Stream::flatMap
- 使用管道字符("|")分割字符串
- 在IntelliJ中找不到Maven插件
- Java List.add() UnsupportedOperationException
- 连接两个字节数组的简单方法
- 为什么Mockito不模拟静态方法?
- Volatile boolean vs AtomicBoolean
- 在一个类中使用相同的方法实现两个接口。覆盖了哪个接口方法?
- 线程的上下文类装入器和普通类装入器之间的区别
- 如何在Java中正确地比较两个整数?
- 在Java中获取“unixtime”