码迷,mamicode.com
首页 > 其他好文 > 详细

反射动态的获取方法

时间:2016-10-03 19:14:57      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:

import java.lang.reflect.Method;

public class ReflectDemo4 {

    public static void main(String[] args) throws Exception {
        
//        getMethodDemo();
        
//        getMethodDemo2();
        
        getMethodDemo3();
        
    }
    //反射方法,非静态,有参数的show方法
    public static void getMethodDemo3() throws Exception{
        
        String className = "cn.qujianlei.domain.Person";
        Class clazz = Class.forName(className);
        
        Method method = clazz.getMethod("paramShow", String.class,int.class);
        
        Object obj = clazz.newInstance();
        
        method.invoke(obj, "xiaoqiang",40);
        
    }
    
    //反射方法,静态,无参数的show方法
    public static void getMethodDemo2() throws Exception{
        
        String className = "cn.qujianlei.domain.Person";
        Class clazz = Class.forName(className);
        
        Method method = clazz.getMethod("staticShow", null);
        
        method.invoke(null, null);
        
        
    }
    
    //反射方法,非静态,无参数的show方法
    public static void getMethodDemo() throws Exception{
        
        String className = "cn.qujianlei.domain.Person";
        Class clazz = Class.forName(className);
        
        Method method = clazz.getMethod("show", null);
        
        Object obj = clazz.newInstance();
        method.invoke(obj, null);
        
    }

}
public class Person {
        
    private String name;
    private int age;
    public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    
    public Person() {
        super();
        System.out.println("person run");
        
    }
    
    public void show(){
        System.out.println("person show run");
    }
    
    public static void staticShow(){
        System.out.println("person static show run");
    }
    
    public void paramShow(String name,int age){
        System.out.println("show:"+name+"---"+age);
    }
    
    
}

 

反射动态的获取方法

标签:

原文地址:http://www.cnblogs.com/qjlbky/p/5929472.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!