try { Class<?> mClass = Class.forName("com.android.server.wifi.WifiSettingsStore"); Constructor con=mClass.getDeclaredConstructor(Context.class); if(!con.isAccessible()){ con.setAccessible(true); } Object store = con.newInstance(this); Method[] methods = mClass.getDeclaredMethods(); Method method = null; for(Method m:methods){ if(m.getName().equalsIgnoreCase("getPersistedScanAlwaysAvailable")){ method = m; break; } } if(!method.isAccessible()){ method.setAccessible(true); } Object a = method.invoke(store); Log.e("a", a.toString()); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch(Exception e){ e.printStackTrace(); }
android系統級api中含有大量的類,當然這些底層類都會被public的api鏈接到,但有時候你可能須要突破系統的限制做一些事情,那這個時候反射就成了利器。
這里不會講反射意義,給出上面的樣例,主要是為了說明。在系統中,凡是存在的類,我們都能夠拿到事實上例。
從而調用當中的私有屬性(非final)和私有方法,從而越過系統的限制。