Re: [問題] 從String 拿到 任意class的constant

看板java作者 (Mr. Pan)時間12年前 (2013/05/18 00:50), 編輯推噓1(103)
留言4則, 3人參與, 最新討論串4/4 (看更多)
: 我是學了五個月java的小小 : 就我最近碰到的, 剛好可以獻醜 : 基本上呢你的className要改, 原本那樣是不行的 : 要改成這樣 : className = "java.lang.Math"; : Type沒有用 : 然後... Magic... : public class Test { : public static void main(String args[]) throws Exception{ : String className = "java.lang.Math"; : String constName = "PI"; : Object obj = : Test.class.getClassLoader().loadClass(className).getDeclaredField(constName).get(null); : System.out.print(obj); : } : } 作為交流 其實可以稍微改一下 import java.lang.reflect.*; public class TEST{ public static void main(String[] args) throws Exception{ Class cls=Class.forName("java.lang.Math"); Field field=cls.getField("PI"); double math_PI=field.getDouble(null); System.out.println(math_PI); } } reflect 也可以存取 private member,某種層面上來看是還蠻強大的XD ? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 122.121.194.188

05/18 01:00, , 1F
不過我看到的code大多object出來後面再判斷
05/18 01:00, 1F

05/18 01:02, , 2F
Class.forName用法不錯 (筆記
05/18 01:02, 2F

05/18 01:21, , 3F
主要是要拿的東西是有明確資料的,所以OK~
05/18 01:21, 3F

05/19 23:50, , 4F
感謝real大與dark大, 獲益良多 thx!
05/19 23:50, 4F
文章代碼(AID): #1Hbb_jJe (java)
討論串 (同標題文章)
文章代碼(AID): #1Hbb_jJe (java)