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

看板java作者 (真肉)時間11年前 (2013/05/17 21:11), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串3/4 (看更多)
※ 引述《PBS3 (PBS3)》之銘言: : 請問版上大大 : 假設我今天有三條String: : String className = "Math"; : String constName = "PI"; : String type = "double"; : 我可以透過甚麼語法拿到 Math.PI ? : 感謝各位~ 我是學了五個月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); } } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.25.44.230
文章代碼(AID): #1HbYntMD (java)
討論串 (同標題文章)
文章代碼(AID): #1HbYntMD (java)