eclipse裏面有很多的地方都體現了反射的因素,現在模範這些做了一個小的應用雖然樣子不是很好看,而且還點地方沒處理好但是能帶到體現其中效果。
先看看最終的界面效果。
這頁面沒有怎麼仔細的去排版和處理,先將就看下
在代碼方面我們需要建立三個類,一個顯示頁面<ReflectJFrame>,一個處理類<Reflect>,一個底層類<Student>
先看看我們的底層類Student,該類沒有什麼多的東西就隨便的寫了些,只是爲了體現效果:
/**
* @author YangJing
*
*/
public class Student {
int a=0;
String yangjing = null;
public Student() {
System.out.println( "Student構造方法!" );
}
public String SayHello(){
String s = "SayHello";
return s;
}
public String myName(){
yangjing = "yangjing";
return yangjing;
}
}
Student類裏面只有兩個公共的字段與三個方法。
處理類Reflect,他裏面有三個方法,分別是得到字段,得到方法以及得到構造方法
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/**
* @author YangJing
*
*/
public class Reflect {
//得到字段
public List<String> getField(String className) throws Exception{
Class c;
try {
c = Class.forName(className);
} catch (ClassNotFoundException e) {
throw new Exception("無法加載該類字段");
}
List<String> fields = new ArrayList<String>();
Field[] f = c.getDeclaredFields();
for (int i = 0; i < f.length; i++) {
fields.add(f[i].getName());
}
return fields;
}
//得到方法
public List<String> getMethod(String className) throws Exception{
Class c;
try {
c = Class.forName(className);
} catch (ClassNotFoundException e) {
throw new Exception("無法加載該類方法");
}
List<String> methods = new ArrayList<String>();
Method[] f = c.getDeclaredMethods();
for (int i = 0; i < f.length; i++) {
methods.add(f[i].getName());
}
return methods;
}
//得到構造方法
public List<String> getConstr(String className) throws Exception{
Class c;
List<String> constructor = new ArrayList<String>();
try {
c = Class.forName(className);
Constructor[] f = c.getConstructors();
for (int i = 0; i < f.length; i++) {
constructor.add(f[i].getName());
}
} catch (ClassNotFoundException e) {
throw new Exception("無法加載該類方法");
}
return constructor;
}
}
頁面顯示類 ReflectJFrame 在這類裏面只是用到了最基本的操作,如事件和麪板這些東西
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/**
* @author YangJing
*
*/
public class ReflectJFrame extends JFrame implements ActionListener{
TextField txtClassName = new TextField(20);
JButton jbuShow = new JButton("顯示"),
jbuexecute = new JButton("執行");
JComboBox combobox = new JComboBox();
TextArea txaMatter = new TextArea(20,30),
txtContent = new TextArea(15,30);
JPanel p1 = new JPanel(new FlowLayout(FlowLayout.LEFT)),
p2 = new JPanel(new FlowLayout(FlowLayout.LEFT)),
p3 = new JPanel(new FlowLayout()),
p4 = new JPanel(new FlowLayout()),
p5 = new JPanel(new BorderLayout());
String s = null;
public ReflectJFrame() {
this.setLayout(new BorderLayout());
this.setTitle("Reflect 反射機制");
this.setSize(500, 400);
this.init();
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public void init(){
//頂部
jbuShow.addActionListener(this);
p1.add(txtClassName);
p1.add(jbuShow);
//右邊
p3.add(combobox);
combobox.addActionListener(this);
p3.add(jbuexecute);
jbuexecute.addActionListener(this);
p4.add(txtContent);
p5.add(p3,BorderLayout.NORTH);
p5.add(p4,BorderLayout.CENTER);
//左邊
p2.add(txaMatter);
this.add(p1,BorderLayout.NORTH);
this.add(p2,BorderLayout.CENTER);
this.add(p5,BorderLayout.EAST);
}
/**
* @param args
*/
public static void main(String[] args) {
new ReflectJFrame();
}
Reflect reflect = new Reflect();
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==jbuShow){
try {
List<String> fields= reflect.getField(this.txtClassName.getText().trim());
StringBuffer str = new StringBuffer("--Field--");
str.append("\n");
for (int i = 0; i < fields.size(); i++) {
str.append(fields.get(i));
str.append("\n");
}
this.txaMatter.setText(str.toString());
List<String> methods = reflect.getMethod(this.txtClassName.getText().trim());
str.append("--Methods--");
str.append("\n");
for (int i = 0; i < methods.size(); i++) {
str.append(methods.get(i));
str.append("\n");
combobox.addItem(methods.get(i));
}
this.txaMatter.setText(str.toString());
List<String> constructor = reflect.getConstr(this.txtClassName.getText().trim());
str.append("--constructors--");
str.append("\n");
for (int i = 0; i < constructor.size(); i++) {
str.append(constructor.get(i));
str.append("\n");
combobox.addItem(constructor.get(i));
}
this.txaMatter.setText(str.toString());
} catch (Exception e1) {
JOptionPane.showMessageDialog(this, e1.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
}
}
if(e.getSource()==jbuexecute){
s=(String)combobox.getSelectedItem();
try {
Class c = Class.forName(this.txtClassName.getText().trim());
//獲得指定的方法
Method m = c.getMethod(s,null);
StringBuffer sr = new StringBuffer();
sr.append(m.invoke(c.newInstance(), null));
this.txtContent.setText(sr.toString());
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (InvocationTargetException e1) {
e1.printStackTrace();
} catch (InstantiationException e1) {
e1.printStackTrace();
}
catch (SecurityException e1) {
e1.printStackTrace();
}catch (NoSuchMethodException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
}
}
}
這只是一個簡單的模型,也是爲了學習的時候更好的體現出效果而做的一個demo,雖然還有些地方還沒有完善!
作者:楊靜(YangJing)
出處: [楊靜の專欄] (博文連接)