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)
出处: [杨静の专栏] (博文连接)