Artikel ini menjelaskan metode implementasi sederhana untuk refleksi Java. Bagikan untuk referensi Anda. Metode implementasi spesifik adalah sebagai berikut:
Salinan kode adalah sebagai berikut: Paket Refleksi;
impor java.io.file;
impor java.io.fileInputStream;
impor java.io.filenotfoundException;
impor java.io.fileoutputStream;
impor java.io.ioException;
impor java.util.properties;
Buah antarmuka {
public abstrak void eat ();
}
Class Apple mengimplementasikan buah {
public void eat () {
System.out.println ("Eat Apple");
}
}
Kelas Oranye mengimplementasikan buah {
public void eat () {
System.out.println ("Eat Orange");
}
}
class init {
Properti statis publik getPro () melempar FileNotFoundException, IoException {
Properti pro = properti baru ();
File f = file baru ("Fruit.Properties");
if (f.exists ()) {
System.out.println ("Ada file konfigurasi!");
// Baca pasangan nilai kunci dari file konfigurasi
pro.load (FileInputStream baru (f));
}kalau tidak{
System.out.println ("Tidak ada file konfigurasi!");
pro.setProperty ("apple", "reflect.apple");
pro.setProperty ("Orange", "Reflect.ORANGE");
pro.store (FileOutputStream baru (f), "kelas buah");
}
Return Pro;
}
}
Pabrik kelas {
getinstance buah statis publik (string className) {
buah f = null;
mencoba {
// Dapatkan objek instance buah melalui refleksi
f = (buah) class.forname (className) .newinstance ();
} catch (InstantiationException e) {
e.printstacktrace ();
} catch (IllegalAccessException e) {
e.printstacktrace ();
} catch (classnotfoundException e) {
e.printstacktrace ();
}
kembali f;
}
}
kelas publik halo {
public static void main (string [] args) {
mencoba {
Properties pro = init.getPro ();
buah f = factory.getInstance (pro.getProperty ("apel"));
if (f! = null) {
f.eat ();
}
} catch (FileNotFoundException e) {
// TODO Blok tangkapan yang dihasilkan otomatis
e.printstacktrace ();
} catch (ioException e) {
// TODO Blok tangkapan yang dihasilkan otomatis
e.printstacktrace ();
}
}
}
Hasilnya adalah:
Ada file konfigurasi!
makan apel
Saya harap artikel ini akan membantu pemrograman Java semua orang.