相关代码及其解释
public class fanshe {
public static void main(String[] args) throws Exception {
// getall();
// geta();
// getObj();
// getMe();
useMe();
}
/*
1):获取方法所在类的字节码对象.
2):获取方法对象.
3):使用反射调用方法.
*/
private static void useMe() throws Exception {
Class<text_fanshe> clz = text_fanshe.class;
Method m = clz.getMethod("method1",String.class);
//用他妈万物之源obj去接收m.invoke()
Object o = m.invoke(clz.newInstance(),"hah");
System.out.println(o);
}
//获取单个构造器
private static void geta() throws Exception {
Class<text_fanshe> clz1 = text_fanshe.class;
//获取无参数构造器
Constructor<?> con1 = clz1.getConstructor();
System.out.println(con1);
//获取带参数构造器
Constructor<?> con2 = clz1.getConstructor(int.class,String.class);
System.out.println(con2);
//获取构造器不是public修饰的构造器
con1 = clz1.getDeclaredConstructor(int.class);
System.out.println(con1);
}
//获取全部构造器
public static void getall() throws Exception {
Class<text_fanshe> clz = text_fanshe.class;
Constructor<?>[] con = clz.getConstructors();
System.out.println(con.length);
for (Constructor<?> o : con) {
System.out.println(o);
}
}
//通过构造器创建对象
public static void getObj() throws Exception {
Class<text_fanshe> clz = text_fanshe.class;
Constructor<?> con = clz.getConstructor();
//无参对象
clz.newInstance();
//有参数,修饰符不为public
con = clz.getDeclaredConstructor(int.class);
con.setAccessible(true);//public相关
con.newInstance(10);
//有多个参数
con = clz.getConstructor(int.class,String.class);
con.newInstance(18,"你好");
}
//获取类中的方法
public static void getMe() throws Exception {
Class<text_fanshe> clz = text_fanshe.class;
//获取类中名为method1的公共方法
Method m = clz.getMethod("method1");
System.out.println(m);
//获取带参数的方法
m = clz.getMethod("method2", int.class);
System.out.println(m);
//修饰符不是public的方法
m = clz.getDeclaredMethod("method3");
System.out.println(m);
//获取类中全部方法
Method[] m1 = clz.getMethods();
System.out.println(m1.length);
for (Method method : m1) {
System.out.println(method);
}
}
}
class text_fanshe {
public text_fanshe() { System.out.println("无参构造器");}
public text_fanshe(int a,String s) {System.out.println("俩参数的构造器"+','+"a"+','+"s");}
private text_fanshe(int b) {System.out.println("单个参数且修饰符为private"+','+"b");}
public String method1(String st) {return st;}
public void method2(int c) {}
private void method3() {}
}