package Reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
interface China{
public static final String name="Rollen";
public static int age=20;
public void sayChina();
public void sayHello(String name, int age);
}
class Person implements China{
public Person() {
}
public Person(String sex){
this.sex=sex;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public void sayChina(){
System.out.println("hello ,china");
}
@Override
public void sayHello(String name, int age){
System.out.println(name+" "+age);
}
private String sex;
}
class ReflectDemo{
public static void main(String[] args) {
Class<?> demo=null;
try{
demo=Class.forName("Reflect.Person");//反射方式创建参数Reflect.Person名称的类demo
}catch (Exception e) {
e.printStackTrace();
}
Constructor<?>cons[]=demo.getConstructors();//从类demo获得构造方法 数组cons[]
for (int i = 0; i < cons.length; i++) {
Class<?> p[]=cons[i].getParameterTypes();//从 数组cons[]获得一个方法参数数组p[]
System.out.print("构造方法: ");
int mo=cons[i].getModifiers();//从 数组cons[]获得修饰符,返回值是INT
System.out.print(Modifier.toString(mo)+" ");//打印修饰符 +空格,用Modifier.toString强转
System.out.print(cons[i].getName());//打印类名
System.out.print("(");
for(int j=0;j<p.length;++j){
System.out.print(p[j].getName()+" arg"+i);//打印调用 参数 数组 的类名 + 参数的序号
if(j<p.length-1){
System.out.print(",");
}
}
System.out.println("){}");
}
}
}
反射获得其他类中的全部构造函数
最新推荐文章于 2024-09-14 18:46:05 发布