首页 > 代码库 > java反射实例

java反射实例

 1 package com.test; 2  3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.lang.reflect.InvocationTargetException; 6 import java.lang.reflect.Method; 7 import java.util.Properties; 8   9 public class Test {10  11     /**12      * 13      * @param b 参数列表14      * @param a15      * @return16      */17     public String a(int b,int a){18         String bb=b+2+"";19         System.out.println(a);20         System.out.println("通过反色");21         return bb;22     }23  24 25     public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {26         27         //读取配置文件获得签名用到的key值28         InputStream inputStream = new Test().getClass().getClassLoader().getResourceAsStream("log4j.properties");29         Properties p = new Properties();30         try{31             p.load(inputStream);32         } catch (IOException e1){33             e1.printStackTrace();34         }35         String a = p.getProperty("234234234"); //方法的字符串变量36         Test test=new Test();37         Class ss = int.class;38         Class sa = int.class;39         Class b[] = new Class[2]; //参数类型数组40         41         b[0] = ss;//第一个参数的类型42         b[1]= sa; //第二个参数的类型43         Method get = test.getClass().getMethod(a,b);44         45                                         //调用方法的类,参数列表46         String aa = (String)get.invoke(test,new Integer(3),new Integer(3));47         System.out.println(aa);48 }49 50 51 log4j.properties52 53 54 234234234=a55 56 57 58 59 60 61     /**62      * 读取路径下的properties文件,获得Properties对象63      * @param path64      * @return Properties65      * @throws IOException66      */67     public static Properties getProperties(String fileName) throws IOException{68         String filePath =  ContentsMethod.class.getResource("/").getPath()+ fileName;69         FileInputStream in = new FileInputStream(new File(filePath));70         Properties p = new Properties();71         p.load(in);72         logger.info("ContentsMethod.getProperties =>加载配置文件"+filePath);73         return p;74     }

 

java反射实例