- 加載:由類加載器完成,找到對應的字節碼,創建一個Class對象
- 鏈接:驗證類中的字節碼,爲靜態域分配空間
- 初始化:如果該類有超類,則對其初始化,執行靜態初始化器和靜態初始化塊
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(); }
輸出結果: