java利用反射调用类的某个方法

java利用反射机制 可以动态调用某个类的某个方法,在 扩展系统功能或提供对外接口时经常用的到。

代码如下:

打印类Print.java

package com.test.reflct;
/**
* 打印类
*
* @date 2015-8-12 下午2:18:42
*/
public class Print { public static void print(String str){
System.out.println("打印测试"+str);
}
}

调用类Test.java:

package com.test.reflct;

import java.lang.reflect.Method;

public class Test {

    /**
*
* @return void
*/
public static void main(String[] args) { try {
//加载类
Class<?> printClass = Class.forName("com.test.reflct.Print");
//获取方法
Method printMethod = printClass.getMethod("print",String.class);
//调用
printMethod.invoke(printClass.newInstance(),"123");
} catch (Exception e) {
e.printStackTrace();
} } }

运行后截图:

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAs8AAABVCAIAAAA5cp7sAAALL0lEQVR4nO3dzZWrRhCGYdJiAiIdFIKjYOUQHIDPwRtv7Ay8lRcSUNVd1d2IrivNve+z8JlB/DRFCT6QPHf4+5///v7nvz//+nf5/Y87AABAbwNpAwAAhCJtAACAWKQNAAAQi7QBAABikTYAAEAs0gYAAIhF2gAAALFIGwAAIBZpAwAAxCJtAACAWKQNAAAQi7QBAABikTYAAEAs0gYAAIhF2gAAALFIGwAAIBZpAwAAxCJtAACAWKQNAAAQ65PSxjqPwzivkZtYpugt4H6/3+/LNEzL/dox/QH98PM5irYdgl+N1zbHe3+dx29UGme0p94dvJXeZJmGiv3QrvP4sx8i0kZldrc5rlGnkGMz01Ic43NGuWBIwdZ5vLinb0sbzxK5y4lDqnYwL+U6j90Pe3dqkMM4r/3SRumaLDabVtHuZKdTOzRwtooraWOZSsda753zmr8/TUWz+/Bk2miuyWc79twunVPz7CCq07hXBu/oJPIOaVzwubA7Sz1slDd0qkTOq/ps8nyh40XmStr4hFuEk2N4sXKvnbj9scnOMobkNl46jqC0sc7jOF47ti9f6no0lVeW5EyxTHKurOhiwueerAvlupY2Sie/ZdrLKCtT7GR7fT0auPWesJI21nkchnGaCkHE3YyogqhNuvy+uNy+FQzypHD2QP4M98nHPpil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65jnmj+yJV/QZT++cU36dOBHufJs4426HQnSxnsU3v71O/M3nDe+Tdp4lujSu+N6qFvnUT1E+KyzR5vrh9b/kDyoZZZpmOYzj7bDpDebL+1wl0J9Tk1O+7iTyy+p470SaQMtvk3a+BTises3PM9/T+8L45+LmuBjkDYAAECsStr4DQAA4BqebQAAgFikDQAAEIu0AQAAYp1IG8MwnFv1MJxdxNuit57H9ItbAQAAoV5JG4MjeVUu6M1pzpBv8e5EimocAQAAb3f12UY+sTolzxAtCaNx6wAA4NM0pQ3v2cP9ctqQU7z/FkbijGq9fQ3ZH7Q5/rrf1201purpAACgl7c92/CecJTTRn1IyzQMX7db+s+LHX8EeL192bmi+d8NBgAAZ4SkjeSRg/dsI/mh8N/8mYqz9fX2tf3Dym5yKMUNHm8AANDd6bTxrk9SZDTxcsyhlDac19bbF482AAAIcC5tvJAt8intn6GYaeOuk4c9Vj9tPD5pWZMpfG8DAIAw574lar50dsob08Z6+yqECr64AQBAhMBvibZ/byP/tTFteKMyg0M5ajyX4vkGAAC9BX5LNJ8neakcLwozVBc00kb+CUpqvX3xbAMAgP7e8H/AmhMLEWT/ufBF0f0l+fczhmHY4kM2+Tn98Zc5+N4GAACB+qeNFxZs/9n8Bkk+BQAAfI7XvyVqTvQWP/tq+8pbNgEAAN6If3EeAADEIm0AAIBYpA0AABCLtAEAAGKRNgAAQCzSBgAAiEXaAAAAsUgbAAAgFmkDAADEIm0AAIBYpA0AABCLtAEAAGKRNgAAQCzSBgAAiEXaAAAAsUgbAAAgFmkDAADEIm0AAIBYpA0AABCLtAEAAGKRNgAAQCzSBgAAiEXaAAAAsUgbAAAgFmkDAADEIm0AAIBYpA0AABCLtAEAAGKRNgAAQCzSBgAAiEXaAAAAsUgbAAAgFmkDAADE+h8gnREe/QvBRQAAAABJRU5ErkJggg==" alt="" />

上一篇:利用java反射调用类的的私有方法--转


下一篇:C# 利用反射动态调用类成员