要求する:
任意のクラスのオブジェクトを作成し、クラスを変更せずにそのメソッドを実行するのに役立つ「フレームワーク」を作成します
成し遂げる:
(1)構成ファイル
(2)リフレクション
ステップ:
(1)作成するオブジェクトの完全なクラス名(パッケージ名。クラス名)と実行するメソッドを構成ファイルに定義します。
(2)プログラムに構成ファイルをロードして読み取ります(Propertiesメソッドを使用)
( 3)Reflectionテクノロジーを使用してクラスファイルをメモリにロードします
(4)オブジェクトを作成します
(5)メソッドを実行します
コードデモ:
これが簡単な学生クラスのデモンストレーションです!
(1)まず、getメソッドとsetメソッド、空のパラメーターと完全なパラメーターを備えたStudentクラスを作成し、toStringメソッド、sleepメソッド、schoolメソッドを書き直します。
学生クラス
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public void sleep(){
System.out.println("sleep,打呼噜");
}
public void school(){
System.out.println("go to school");
}
}
(2)新しいファイルを右クリックし、ファイル名、完全なクラス名、および構成ファイルに必要なオブジェクトの実行方法を入力します。これは、Studntクラスの2つの方法、sleepとschoolです。
構成ファイル:
className=Student//(全类名,这里直接在src内操作,所有可以省略包名,一般都是包名.类名)
methodName=sleep//(sleep方法)
methodName1=school//(school方法)
(3)クラスのテスト、構成ファイルの読み取り、リフレクションテクノロジーの使用、オブジェクトの作成、およびメソッドの実行
テストカテゴリ:
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Properties;
public class ReflectTest {
public static void main(String[] args) throws Exception {
//创建Properties对象
Properties p = new Properties();
//获取class目录下的配置文件
ClassLoader classLoader = ReflectTest.class.getClassLoader();
InputStream is = classLoader.getResourceAsStream("puge.yiyan");
//调用load方法加载配置文件,转换为一个集合
p.load(is);
//获取配置文件中定义的数据
String className = p.getProperty("className");
String methodName = p.getProperty("methodName");
String methodName1 = p.getProperty("methodName1");
//加载该类进内存
Class cls = Class.forName(className);
//创建对象
Object obj = cls.newInstance();
//获取方法对象
Method method = cls.getMethod(methodName);
Method method1 = cls.getMethod(methodName1);
//执行方法
method.invoke(obj);
method1.invoke(obj);
}
}
結果:
sleep,打呼噜
go to school