反射练习

郁闷,浪费人感情,好不容易写了满满一篇,提交失败,重新再写!?

下面的例子是我做反射练习的一个例子,用来从一个类中获得public的成员变量,构造函数以及方法,

如果你想获得更private或protected的方法,请自己在代码中修改。

该类提供了2个接口,一个用来指定类名,如“java.util.ArrayList”

另一个就是执行的方法。public String getDatail()

(英文注释有点烂,望谅解,我这是个日文系统,没法写中文注释)

import  java.lang.reflect.Constructor;
import  java.lang.reflect.Field;
import  java.lang.reflect.Method;
import  java.lang.reflect.Modifier;

/**
 * This class is used to find the Fields and Methods declared in
 * the underline class.
 * 
 * 
@author Administrator
 *
 
*/

public   class  FindClassInfo  {
    
    
//store the outPut info
    private StringBuffer strInfo = null;
    
    
//store the class name
    private String strClassName = null;
    
    
private String strSpace = " ";
    
    
private String strNextLine = " ";
    
    
    
/**
     * Set the name of class,which will be showed datail info.
     * 
     * 
@param str
     
*/

    
public void setClassName(String str){
        strClassName 
= str;
    }

    
    
public String getDatail(){
        
if(strClassName == null){
            
return "Please set the Name of Class!";
        }

        Class c 
= null;
        
try {
            c 
= Class.forName(strClassName);
        }
 catch (ClassNotFoundException e) {
            
return "The Class can`t been find by the name!";
        }

        strInfo 
= new StringBuffer();
        strInfo.append(
"----------------------detail of Class:"+strClassName +"----------------------");
        strInfo.append(strNextLine);
        getFields(c);
        getConstructor(c);
        getMethods(c);
        getSuperClssInfo(c);
        
return strInfo.toString();
    }

    
    
/**
     * Get public Fields of Class.
     * 
@param c
     
*/

    
private void getFields(Class c){
        Field[] arrFields 
= c.getDeclaredFields();
        
for(Field tempField:arrFields){
            
//Scape the Private,Default and Protected Field
            if(!Modifier.isPublic(tempField.getModifiers())){
                
continue;
            }

            
            strInfo.append(Modifier.toString(tempField.getModifiers()));
            strInfo.append(strSpace);
            strInfo.append(forTypeName(tempField.getType().getName()));
            strInfo.append(strSpace);
            strInfo.append(forName(tempField.getName()));
            strInfo.append(strNextLine);
        }

    }


    
/**
     * Get public  Constructor.
     * 
@param c
     
*/

    
private void getConstructor(Class c){
        Constructor[] arrConstructor 
= c.getDeclaredConstructors();
        
for(Constructor tempCons : arrConstructor){
            
//Scape the Private,Default and Protected Constructor
            if(!Modifier.isPublic(tempCons.getModifiers())){
                
continue;
            }

            strInfo.append(Modifier.toString(tempCons.getModifiers()));
            strInfo.append(strSpace);
            strInfo.append(forName(tempCons.getName()));
            strInfo.append(
"(");
            Class[] arrParaTypes 
= tempCons.getParameterTypes();
            
for(int i=0;i<arrParaTypes.length;i++){
                strInfo.append(forTypeName(arrParaTypes[i].getName()));
                
if(i<arrParaTypes.length -1){
                    strInfo.append(
",");
                }

            }

            strInfo.append(
")");
            strInfo.append(strNextLine);
        }

            
    }

    
    
/**
     * Get public method of Class
     * 
@param c
     
*/

    
private void getMethods(Class c){
        Method[] arrMethod 
= c.getDeclaredMethods();
        
for(Method tempMethod:arrMethod){
            
//Scape the Private,Default and Protected Method
            if(!Modifier.isPublic(tempMethod.getModifiers())){
                
continue;
            }

            strInfo.append(Modifier.toString(tempMethod.getModifiers()));
            strInfo.append(strSpace);
            strInfo.append(forTypeName(tempMethod.getReturnType().getName()));
            strInfo.append(strSpace);
            strInfo.append(forName(tempMethod.getName()));
            strInfo.append(
"(");
            Class[] arrParaTypes 
= tempMethod.getParameterTypes();
            
for(int i=0;i<arrParaTypes.length;i++){
                strInfo.append(forTypeName(arrParaTypes[i].getName()));
                
if(i<arrParaTypes.length -1){
                    strInfo.append(
",");
                }

            }

            strInfo.append(
")");
            strInfo.append(strNextLine);
        }

    }

    
    
private void getSuperClssInfo(Class c){
        
if(c.getSuperclass().getName().equals(Object.class.getName())){
            
return;
        }

        Class superClass 
= c.getSuperclass();
        getSuperClssInfo(superClass);
        strInfo.append(
"------------Fields inherited from "+superClass.getName()+"----------------");
        strInfo.append(strNextLine);
        getFields(superClass);
        strInfo.append(strNextLine);
        strInfo.append(
"------------Methods inherited from "+superClass.getName()+"----------------");
        strInfo.append(strNextLine);
        getMethods(superClass);
    }

    
/**
     * Get name from InputString.
     * This method is used to Get name of Class except TypeClass.
     * 
     * 
@param str .class Name or method name or Field name.
     * 
@return
     
*/

    
private String forName(String str){
        
return str.substring(str.lastIndexOf(".")+1);
    }

    
    
/**
     * Get name from InputString,and the inputString is the original name of
     * Clss which refered to Type.
     * The name of ReturnType have three kinds.
     * one  matches "[*[B,C,S,I,D,J,F]",this is primitive type array.
     * one mathes "[*S+;",This is Object type array.
     * one is not array.
     * 
     * 
@param str
     * 
@return the String imply Type.
     
*/

    
private String forTypeName(String str){
        String tempStr 
= "";
        
//return type is array
        if(str.startsWith("[")){
            
switch(str.charAt(str.lastIndexOf("[")+1)){
            
case 'B':
                tempStr 
= "byte";
                
break;
            
case 'C':
                tempStr 
= "char";
                
break;
            
case 'S':
                tempStr 
= "short";
                
break;
            
case 'I':
                tempStr 
= "int";
                
break;
            
case 'D':
                tempStr 
= "double";
                
break;
            
case 'J':
                tempStr 
= "long";
                
break;
            
case 'F':
                tempStr 
= "float";
                
break;
                
//Return-Type is array of Object
            case 'L':
                tempStr 
= str.substring(str.lastIndexOf(".")+1,str.length()-1);
            
default:
                    
break;
            }

            
            
//add "[]"
            int arrCount = str.lastIndexOf("[")+1;
            
for(int i= 0;i<arrCount;i++){
                tempStr 
+="[]";
            }

        }
else{
            tempStr 
= str.substring(str.lastIndexOf(".")+1);
        }

        
return tempStr;
    }

}

 

希望了解反射的朋友,看了之后能给我点建议,不太了解的朋友,可以拿这个例子跑跑,顺便熟悉以下反射。

谢过了,学习中。。。。。。。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值