通过java反射机制调用类中方法

package test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Car {

    public String qryInfo(String name, String contry, Integer num) {
        return name + "车, 产地在" + contry + ", 年产"+ num + "台";
    }

    public static void main(String[] args) {
        try {
            Class clazz = Class.forName("test.Car");
            Method method = clazz.getDeclaredMethod("qryInfo", String.class, String.class, Integer.class);
            Object obj = method.invoke(clazz.newInstance(), "大众","上海", 20000);
            System.out.println(obj);
        } catch (ClassNotFoundException e) {
			e.printStackTrace();
		}catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		}catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		}
    }
}

 

你可能感兴趣的:(通过java反射机制调用类中方法)