- package com.itcast.practise;
- import java.lang.reflect.Constructor;
- import java.lang.reflect.Method;
- public class Demo1 {
- public static void main(String[] args)throws Exception{
-
- Constructor constructor = Person.class.getConstructor(int.class,String.class); //得到构造函数
- Person s =(Person) constructor.newInstance(25,"小明"); //创建实例对象
- System.out.println(s.age + "," + s.name); //打印实例对象属性
-
- constructor = Person.class.getConstructor(); //得到无参数的构造函数
- Person s1 = (Person)constructor.newInstance();
- System.out.println(s1.age + "," + s1.name); //打印实例对象属性
-
- Method method = Person.class.getMethod("study"); //得到study函数
- method.invoke(s); //调用实例s中的study方法
-
- }
- }
- class Person{
- int age = 10;
- String name = "小华" ;
- public void study(){
- System.out.println("好好学习");
- }
- public Person(int age,String name){ //这里的构造函数必须声明为public,否则编译失败
- this.age = age;
- this.name = name;
-
- }
- public Person(){
-
- }
- }
复制代码 |