1. 程式人生 > >java類的動態類加載

java類的動態類加載

except pac () 加載 art ann fff [] pub

萬物皆對象

類是java.lang.Class的對象

package com.mysec.reflex;
import java.util.Scanner;
//任何一個類都是Class的實例對象
public class OfficeBeffer {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
methodStart(name);
}

public static void methodStart(String name){
try {

//知道該類的對象通過getClass方法
// test c1 = new test();
// c1.getClass();
//任何一個類都有一個隱含的靜態成員變量
// Class<?> c2 = test.class;

//動態加載類,在運行時刻加載
//com.mysec.reflex.Word
Class<?> c = Class.forName(name);


//通過類類型,創建該類的對象
OfficeAble oa = (OfficeAble)c.newInstance();
oa.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}



package com.mysec.reflex;
public interface OfficeAble {
public void start();
}

package com.mysec.reflex;
public class Word implements OfficeAble{
@Override
public void start() {
System.out.println("wordStarts...");
}
}

java類的動態類加載