Java 解惑知多少六
41. instanceof与转型
System.out.println(null instanceof String);//false System.out.println(new Object() instanceof String);//false //编译能通过 System.out.println((Object) new Date() instanceof String);//false //!!程序不具有实际意义,但编译时不能通过 //!!System.out.println(new Date() instanceof String); //!!运行时抛ClassCastException,这个程序没有任何意义,但可以编译 //!!System.out.println((Date) new Object());
public class P { private int x, y; private String name; P(int x, int y) { this.x = x; this.y = y; // 这里实质上是调用子类被重写的方法 name = makeName(); } protected String makeName() { return "[" + x + "," + y + "]"; } public String toString() { return name; } } class S extends P { private String color; S(int x, int y, String color) { super(x, y); this.color = color; } protected String makeName() { return super.makeName() + ":" + color; } public static void main(String[] args) { System.out.println(new S(1, 2, "red"));// [1,2]:null } } public class T { public static int i = prt(); public static int y = 1; public static int prt() { return y; } public static void main(String[] args) { System.out.println(T.i);// 0 } } public class Outer { public class Inner { public String toString() { return "Hello world"; } } public void getInner() { try { // 普通方式创建内部类实例 System.out.println(new Outer().new Inner());// Hello world //!! 反射创建内部类,抛异常:java.lang.InstantiationException:Outer$Inner System.out.println(Inner.class.newInstance()); } catch (Exception e) { } } public static void main(String[] args) { new Outer().getInner(); } } Constructor c = Inner.class.getConstructor(Outer.class);//获取带参数的内部类构造函数 System.out.println(c.newInstance(Outer.this));//反射时还需传进外围类