public class Base { static int num = 1; static { System.out.println("Base " + num); } } public class Main { public static void main(String[] args) { // 不会初始化静态块 Class clazz1 = Base.class; System.out.println("------"); // 会初始化 Class clazz2 = Class.forName("zzz.Base"); } }
class Base { } class Derived extends Base { } public class Main { public static void main(String[] args) { Base base = new Derived(); if (base instanceof Derived) { // 这里可以向下转换了 System.out.println("ok"); } else { System.out.println("not ok"); } } }
class Base { } class Derived extends Base { } public class Main { public static void main(String[] args) { Base base = new Derived(); if (base instanceof Derived) { // 这里可以向下转换了 System.out.println("ok"); } else { System.out.println("not ok"); } } }
public interface Hello { void doSomething(); } public class HelloImpl implements Hello { @Override public void doSomething() { System.out.println("HelloImpl doSomething"); } } /** * 代理类 */ public class ProxyHandler implements InvocationHandler { private Object proxyed; public ProxyHandler(Object proxy) { proxyed = proxy; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws InvocationTargetException, IllegalAccessException { System.out.println("proxy working"); return method.invoke(proxyed, args); } } public static void main(String[] args) { Hello hello = new HelloImpl(); Hello proxy = (Hello) Proxy.newProxyInstance(Hello.class.getClassLoader(), new Class[]{Hello.class}, new ProxyHandler(hello)); proxy.doSomething(); }
输出结果:
【Java核心技术】类型信息(Class对象 反射 动态代理)
原文:http://www.cnblogs.com/luoxn28/p/7100713.html