java如何用反射獲取類實例?
想了解更多Java相關,百度搜索圈T社區,免費視頻教程。純干貨
public class demo {private String key1 = "1";private String key2 = "2";public String getKey1() {return key1;}public void setKey1(String key1) {this.key1 = key1;}public String getKey2() {return key2;}public void setKey2(String key2) {this.key2 = key2;}public static void main(String[] args) throws Exception {//參數 “Demo” 是類的全名,如果在包結構下,要有完整包路徑 比如: com.test.DemoClass<?> clazz = Class.forName("Demo");//“Demo”類必須有默認構造方法,否則會拋出異常Demo demo = (Demo) clazz.newInstance();System.out.println(demo.getKey1());System.out.println(demo.getKey2());}}