java反射机制
?øjava??ÉäµÄ??Ì??˵?Éú?ÉÀà
ÔðÈÎ?à?,?ºadmin ×?Õß?º Ê??ä?º2005-07-18 À?Ô??º µã??Êý?º32
/*
* createObjectMenu.java
*
* Created on 2005Äê4ÔÂ16ÈÕ, ÏÂÎç10:28
*/
package src;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.*;
import java.lang.reflect.*;
/**
*
* @author ForTest
*/
public class createObjectMenu {
/** Creates a new instance of createObjectMenu */
public createObjectMenu() {
}
public JMenuBar createFunction(String user) throws SQLException{
Connection con=cc.getConn();
String sql="select mname,paren,mtype,mjb from Menu where user='"+user+"'and
mtype='Menu';";
try{
Statement stmt= con.createStatement();
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()){
if(rs.getInt("mjb")==1){
MenuBarTest.add(getUserMenu(user,rs.getString("mname")));
}
}
}catch(SQLException e){
System.err.println("createFunction:"+e.getMessage());
}
return MenuBarTest;
}
public JMenu getUserMenu(String user,String paren) throws SQLException{ //µÃµ?MENU×Ó?˵?
Connection con=cc.getConn();
String sql="select mname,mtype from Menu where user='"+user+"'and paren='"+paren+"';";
JMenu tmpMenu=new JMenu(paren);
try{
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()){
if(rs.getString("mtype").equals("Item")){
tmpMenu.add(getUserItem(rs.getString("mname")));
}else{
tmpMenu.add(getUserMenu(user,rs.getString("mname")));
}
}
}catch(SQLException e){
System.err.println("getUserMenu:"+e.getMessage());
}
return tmpMenu;
}
public JMenuItem getUserItem(String mname){
JMenuItem tmpItem =new JMenuItem(mname);
tmpItem.addActionListener(tmpListener); //Ìí?Ó?àÌý
return tmpItem;
}
ActionListener tmpListener = new ActionListener() { //????Ò??ö?àÌýÆ?
public void actionPerformed(ActionEvent event) {
JMenuItem tmpItem=(JMenuItem)event.getSource();
String addAction=tmpItem.getText()+"Action";
getListener(addAction);
}
};
public void getListener(String
methListener){ //java??ÉäÓ?ÓÃ??Í??ýº?ÊýÃû?ÆÀ???Ì?µ?Óú?Êý
try{
Class cls=Class.forName("src.MenuItemListener"); //µÃµ?ÒªÔÚÆäÖÐ?éÕÒ????µÄÀà
Class partypes[] = new Class[]{}; //º?Êýµ?ÓõÄ?ÎÊýÀàÐÍ??ÕâÀïΪ?Õ??
Method moth=cls.getMethod(methListener, partypes); //µÃµ?????
MenuItemListener ml=new MenuItemListener(); //ÒÔMenuItemListener??ÔìÒ??öеÄ?ÔÏó
Object[] obj=new Object[]{}; //Éú?ɺ?ÊýÒªµ?ÓõÄÊý?Ý??ÕâÀïΪ?Õ??
Object r=moth.invoke(ml, obj); //µ?Óõõ?µÄº?Êý??
}catch(Throwable e){
System.err.println(e); //Å×?öÒì????
}
}
JMenuBar MenuBarTest=new JMenuBar();
ConnClass cc=new ConnClass();
}
/*
??ÀàÍ??ýAccessÊý?Ý?âÖÐÒ??öMenu?í??Á??˵????í?á??ÈçÏÂ
mid:?˵?µÄidºÅ??×Ô??Ôö?Ó
manme:?˵?Ãû?Æ
mtype:?˵?ÀàÐÍ
paren:ÉÏÒ????˵?Ãû?Æ
mjb:?˵????ð
ConnClass ÀàΪÒ??öÖ?ÓÃÀ?×öÊý?Ý?âÁ??ÓµÄÀà??????getConn()?µ?ØÒ??öÁ??Ó getListener(String
methListener)ÊÇÒ??öjava??ÉäµÄÓ?ÓÃ??ÓÃÀ?Í??ýÒ??ö?ø??µÄ×Ö?û???éÕÒÒ??ö??????Ö?ÐÐ