01.反射01

package com.qq.oop;

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

public class yongFanShe {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
Class c1 = Class.forName("com.qq.oop.teacher");
//怎么用 反射得到的这个c1 用方法,属性,构造方法呢>>>>>

//1.先总的搞个new一样的东西出来吧

//这是第一种,无参构造方法,造个对象
// Object bb = c1.newInstance();
// // bb=(teacher)bb;
// System.out.println(((teacher) bb).age);
// ((teacher) bb).setAge(100);
// System.out.println(((teacher) bb).age);
//有参怎么造呢?
// Object wo = c1.newInstance(int.class,String.class); 这样搞好像不行
//通过得到构造器搞
// Constructor dc = c1.getDeclaredConstructor(int.class);
// teacher nihoa =(teacher) dc.newInstance(999);
// System.out.println(nihoa);

//通过反射 用方法
teacher t1 =(teacher) c1.newInstance();
// t1.setAge(10);
// System.out.println(t1.getAge()); 这样就可以调用方法了,还搞什么
Method getAge = c1.getDeclaredMethod("setAge",int.class);
getAge.invoke(t1,1000);
System.out.println(t1.getAge());
}
}
class teacher{
int age=10;

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public teacher() {
}

public teacher(int age) {
this.age = age;
}
}

猜你喜欢

转载自www.cnblogs.com/amszdj/p/12953747.html
01.