public class main {
public static void main(String[] args) throws Exception{
Class clazz=student.class;
/*getConstructors()获取当前运行时类中声明为public的构造器*/
Constructor[] constructors=clazz.getConstructors();
for(Constructor c:constructors){
System.out.println(c);
}
/*getDeclaredConstructors()获取当前运行时类中所有的构造器*/
Constructor[] declaredConstructors = clazz.getDeclaredConstructors();
for(Constructor c:declaredConstructors){
System.out.println(c);
}
}
}
获取带泛型父类的泛型
public class main {
public static void main(String[] args) throws Exception{
Class clazz=student.class;
/*获取带泛型的父类的泛型*/
Type genericSuperclass = clazz.getGenericSuperclass();
ParameterizedType para=(ParameterizedType)genericSuperclass;
//获取泛型类型
Type[] actualtype= para.getActualTypeArguments();
System.out.println(actualtype[0].getTypeName());
}
}
获取运行时类的接口 、所在包、注解
public class main {
public static void main(String[] args) throws Exception{
Class clazz=student.class;
Class[] interfaces = clazz.getInterfaces();
for(Class c:interfaces){
System.out.println(c);
}
/*获取运行时类所在的包*/
Package aPackage = clazz.getPackage();
/*获取运行时类的声明的注解*/
Annotation[] annotations = clazz.getAnnotations();
}
}
调用运行时类中指定的结构:属性
public class main {
public static void main(String[] args) throws Exception {
Class clazz = student.class;
/*创建运行时类对象*/
student obj = (student) clazz.getDeclaredConstructor().newInstance();
/*获取指定的属性*/
Field age = clazz.getDeclaredField("age");
/*保证当前属性可以访问*/
age.setAccessible(true);
/*
设置当前属性值
set():参数1 指明设置的对象
参数2 参数属性值
*/
age.set(obj, 101);
/*
获取当前属性值
get():参数1 获取那个对象的当前属性值
*/
System.out.println(age.get(obj));
}
}
调用运行时类中指定的结构:方法
public class main {
public static void main(String[] args) throws Exception {
Class clazz = student.class;
/*创建运行时类对象*/
student obj = (student) clazz.getDeclaredConstructor().newInstance();
/*
获取指定的方法
getDeclaredMethod():参数1 指明方法名称
参数2 形参列表
*/
Method declared = clazz.getDeclaredMethod("setName", String.class);
declared.setAccessible(true);
/*
invoke():参数1 方法的调用者
参数2 给方法形参赋值的实参
invoke的返回值即为对应方法的返回值
*/
Object returnobj = declared.invoke(obj, "abc");
System.out.println((String) returnobj);
/*调用静态方法*/
Method show = clazz.getDeclaredMethod("show");
show.setAccessible(true);
Object reobn1=show.invoke(student.class);
System.out.println(reobn1);
}
}
调用运行时类中指定的结构:构造器
public class main {
public static void main(String[] args) throws Exception {
Class clazz = student.class;
/*获取指定的构造器*/
Constructor declaredConstructor = clazz.getDeclaredConstructor(String.class);
declaredConstructor.setAccessible(true);
student tom =(student)declaredConstructor.newInstance("tom");
}
}