题目:
请用户在控制台输入一个类的完整类名
com.ref.bean.Dog
然后在控制台中输出这个类的详细信息
包括全部的方法和属性
全部的构造方法
父类
所属的包
父类私有方法
package work.test01;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test02 {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
/* System.out.println("请输入完整类名:");
Scanner sc = new Scanner(System.in);
//work.test01.Man
String path = sc.next();*/
Class<?> clazz = Class.forName("work.test01.Man");
Object manClass = clazz.newInstance();
System.out.println("详细信息:");
//包括全部的方法和属性
Method[] methods = clazz.getMethods();
for (int i = 0; i < methods.length; i++) {
System.out.println("方法"+i+"--"+methods[i]);
}
//调用类中属性
Field[] fields = clazz.getFields();
for (Field field : fields) {
System.out.println("属性:"+field);
}
//全部的构造方法
Constructor<?>[] declaredConstructors = clazz.getDeclaredConstructors();
for (Constructor<?> declaredConstructor : declaredConstructors) {
System.out.println("构造方法 ==>"+declaredConstructor);
}
//父类
Class<?> superclass = clazz.getSuperclass();
//实例化父类对像
Object superClass = superclass.newInstance();
//调用父类public方法
Method method11 = superclass.getDeclaredMethod("method1");
method11.invoke(superClass);
//调用父类private方法
Method method2 = superclass.getDeclaredMethod("method2");
method2.setAccessible(true);
Object invoke1 = method2.invoke(superClass);
System.out.println("父类:"+superClass);
//所属的包
Package clazzPackage = clazz.getPackage();
System.out.println("所属包:"+clazzPackage);
}
}
class Person {
private String name="二狗子";
private int age=18;
public Person(){}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void method1(){
System.out.println("我是父类public方法");
}
private void method2(){
System.out.println("我是父类private方法");
}
}
class Man extends Person{
private String like="打乒乓";
public Man(){}
public Man(String like) {
this.like = like;
}
public Man(String name, int age, String like) {
super(name, age);
this.like = like;
}
public String getLike() {
return like;
}
public void setLike(String like) {
this.like = like;
}
public void method(){
System.out.println("Man自定义方法");
super.method1();
}
}
运行结果: