2018-11-19 反射

反射:運(yùn)行時(shí)類(lèi)信息

Person person = new Person("luoxn28", 23);

? ? Class clazz = person.getClass();

? ? Field[] fields = clazz.getDeclaredFields();

? ? for (Field field : fields) {

? ? ? ? String key = field.getName();

? ? ? ? PropertyDescriptor descriptor = new PropertyDescriptor(key, clazz);

? ? ? ? Method method = descriptor.getReadMethod();

? ? ? ? Object value = method.invoke(person);

? ? ? ? System.out.println(key + ":" + value);

? ? }

4、動(dòng)態(tài)代理

public interface Interface {

? ? void doSomething();

? ? void somethingElse(String arg);

}

public class RealObject implements Interface {

? ? public void doSomething() {

? ? ? // System.out.println("doSomething.");

? ? }

? ? public void somethingElse(String arg) {

? ? ? // System.out.println("somethingElse " + arg);

? ? }

}

public class DynamicProxyHandler implements InvocationHandler {

? ? private Object proxyed;


? ? public DynamicProxyHandler(Object proxyed) {

? ? ? ? this.proxyed = proxyed;

? ? }


? ? @Override

? ? public Object invoke(Object proxy, Method method, Object[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {

? ? ? ? System.out.println("代理工作了.");

? ? ? ? return method.invoke(proxyed, args);

? ? }

}

RealObject real = new RealObject();

? ? ? ? Interface proxy = (Interface) Proxy.newProxyInstance(

? ? ? ? ? ? ? ? Interface.class.getClassLoader(), new Class[] {Interface.class},

? ? ? ? ? ? ? ? new DynamicProxyHandler(real));


? ? ? ? proxy.doSomething();

? ? ? ? proxy.somethingElse("luoxn28");

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,695評(píng)論 19 139
  • 深入理解Class對(duì)象 RRTI的概念以及Class對(duì)象作用 認(rèn)識(shí)Class對(duì)象之前,先來(lái)了解一個(gè)概念,RTTI(...
    架構(gòu)師springboot閱讀 1,656評(píng)論 0 3
  • 多態(tài) 任何域的訪(fǎng)問(wèn)操作都將有編譯器解析,如果某個(gè)方法是靜態(tài)的,它的行為就不具有多態(tài)性 java默認(rèn)對(duì)象的銷(xiāo)毀順序與...
    yueyue_projects閱讀 1,096評(píng)論 0 1
  • 想要掌握就好像想要總結(jié),想要總結(jié)舊相當(dāng)于想要客觀(guān)在外,這是為什么呢? 是融于生活會(huì)有什么危險(xiǎn),還是融于生活中,...
    bangjieuu閱讀 86評(píng)論 0 0
  • 心底多情才興奮,筆端無(wú)句不精神。 風(fēng)光在目年年好,四季不同頻寫(xiě)真。
    雪窗_武立之閱讀 206評(píng)論 0 0

友情鏈接更多精彩內(nèi)容