反射執行個體2

來源:互聯網
上載者:User
package com.hsj;import java.lang.reflect.Method;import org.junit.Test;/** * 說明:學生類繼承Person類 如果學生類複寫了eat方法,則調用學生類的eat方法 利用反射擷取Person的受保護的方法 eat方法 * 知識點:利用Class對象的相關方法擷取父類受保護的方法 *  */public class ExtendsReflect {@Testpublic void test() {try {/** * 使用class.forName()擷取位元組碼對象 等同於 Strudent.class(),student.getClass() * student 是Student 的執行個體對象 */Class clazz = Class.forName("com.hsj.domain.Student");Method method = null;while (true) {try {// 擷取eat方法,如果擷取到了,我們就結束迴圈,否則,遞迴調用父類的位元組碼對象的相應方法,如果位元組碼對象是Object,退出迴圈method = clazz.getDeclaredMethod("eat", null);break;} catch (NoSuchMethodException e) {if (clazz == Object.class){System.out.println("沒有對應的方法");break;}/** * 這段代碼是用來擷取父類的位元組碼對象  */clazz = clazz.getSuperclass();}}/** * 如果找到了相應的方法 */if (method != null) {if(!method.isAccessible()){method.setAccessible(true);}method.invoke(clazz.newInstance(), null);}} catch (Exception e) {e.printStackTrace();}}}

package com.hsj.domain;public class Student extends Person {public void learn(){System.out.println("學生的學習方法");}@Overrideprotected void eat() {System.out.println("重寫過的eat方法");}}

package com.hsj.domain;public class Person {private String username;private String password;public Person(String username, String password) {super();this.username = username;this.password = password;}public Person() {super();}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public static void main(String[] args) {if(args!=null){for(String s :args){System.out.println(s);}}System.out.println("反射main函數測試");}public void test1(char[] chars){System.out.println("test1 char[]");}public void test2(Integer[] ints){System.out.println("test2...");}public void test3(String s1,String s2){System.out.println("test3");}@Overridepublic String toString() {return this.username+":"+this.password;}protected void eat(){System.out.println("受保護的方法 eat....");}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.