- package com.wxy001;
- import java.lang.reflect.Constructor;
- import java.lang.reflect.Method;
- public class RefelectTest8
- {
-
- public static void main(String[] args) throws Exception
- {
- Class<?> clazz = TestRefelect.class; //加载类,获得Sample类的TestRefelect对象
- Constructor<?> con = clazz.getConstructor(String.class);//加载构造函数
- String str = "反射";
- TestRefelect t = (TestRefelect) con.newInstance(str);//创建TestRefelect对象
- Method method = TestRefelect.class.getMethod("print");//获得实例方法
- method.invoke(t);//调用该方法
- }
- }
- class TestRefelect
- {
- public String str;
- public TestRefelect(String str) {
- // TODO Auto-generated constructor stub
- this.str = str;
- }
-
- public void print()
- {
- System.out.println(str);
- }
- }
复制代码 |
|