package _5_33;
import java.lang.reflect.*;
public class ClassDemo {
public static void main(String[] args) {
try {
Class<?> cls = Class.forName("code0508.Person");
Constructor<?> ct = cls.getConstructor(int.class);
Object obj = ct.newInstance(20); // Create an instance of Person using the constructor
// Get all methods of the class
Method[] methods = cls.getDeclaredMethods();
for (Method m : methods) {
System.out.print(Modifier.toString(m.getModifiers()) + " " + m.getReturnType().getName() + " " + m.getName() + "(");
Class<?>[] params = m.getParameterTypes();
for (Class<?> p : params) {
System.out.print(p.getName() + " ");
}
System.out.println(")");
}
// Call a specific method
Method meth = cls.getMethod("addAge", int.class);
Object retObject = meth.invoke(obj, 5); // Invoke addAge with parameter 5
System.out.println("After addAge(): " + retObject);
// Get all fields of the class
Field[] fields = cls.getDeclaredFields();
for (Field f : fields) {
System.out.print(Modifier.toString(f.getModifiers()) + " " + f.getType().getName() + " " + f.getName() + "; ");
}
System.out.println();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Person {
private String name;
private int age;
public Person() {
this.name = "default";
this.age = 0;
}
public Person(String name) {
this.name = name;
this.age = 0;
}
public Person(int age) {
this.name = "null";
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String toString() {
return "[" + this.name + " " + this.age + "]";
}
public int addAge(int a) {
return age + a;
}
}
class GetConstructor {
public static void main(String[] args) {
Class<?> demo = null;
try {
demo = Class.forName("code0508.Person");
} catch (Exception e) {
e.printStackTrace();
}
// Get all constructors
Constructor<?>[] cons = demo.getConstructors();
try {
Constructor<?> cons0 = demo.getConstructor();
Constructor<?> cons1 = demo.getConstructor(String.class);
Constructor<?> cons2 = demo.getConstructor(int.class);
Constructor<?> cons3 = demo.getConstructor(String.class, int.class);
Person per1 = (Person) cons0.newInstance();
Person per2 = (Person) cons1.newInstance("ZhangShan");
Person per3 = (Person) cons2.newInstance(20);
Person per4 = (Person) cons3.newInstance("Lisi", 20);
System.out.println(per1); // [default 0]
System.out.println(per2); // [ZhangShan 0]
System.out.println(per3); // [null 20]
System.out.println(per4); // [Lisi 20]
} catch (Exception e) {
e.printStackTrace();
}
}
}
1085

被折叠的 条评论
为什么被折叠?



