people代码如下:
package com.wzd.tool;
public class People {
private String name;
private String sex;
private int age;
public People(){
System.out.println("构造方法被调用了啊!");
}
public People(String name){
this.name=name;
System.out.println("构造方法被调用了啊!+String");
}
public People(int age){
this.age=age;
System.out.println("构造方法被调用了啊!+int");
}
private People(String name,String sex){
this.name=name;
this.sex=sex;
System.out.println("构造方法被调用了啊!+name +sex");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void print(){
System.out.println("this man is 36 years old");
}
public void print(String sex,int age){
System.out.println("this"+ sex+" is "+age+" years old");
}
public static int[] print(String name,String sex,int age){
System.out.println("this "+ sex+" called "+name+" is "+age+" years old");
int[] list={1,2,3,4,5,6,7};
return list;
}
private String[] getPersonalInfo(){
System.out.println("the superman is 邓超");
String[] info={"邓超","李晨","王祖蓝","王宝强","Baby","郑凯","陈赫"};
return info;
}
}
<span style="white-space:pre"> </span>放射获取方法如下:
</pre><pre name="code" class="java"><span style="white-space:pre"> </span>public static void main(String[] args){
System.out.println("这里是main方法()");
}
/*
* 反射执行people的print()方法
* */
@Test
public void test1() throws Exception{
Class<People> clazz1=People.class;
Method method=clazz1.getMethod("print", null);
method.invoke(new People(), null);
}
/*
* 反射执行people的print(String name,String sex)方法
* */
@Test
public void test2() throws Exception{
Class<People> clazz1=People.class;
Method method=clazz1.getMethod("print", String.class,int.class);
method.invoke(new People(), "man",25);
}
/*
* 反射执行people的print(String name,String sex,int age)方法(有返回值,静态方法)
* */
@Test
public void test3() throws Exception{
Class<People> clazz1=People.class;
Method method=clazz1.getMethod("print", String.class,String.class,int.class);
//调用静态方法可以不用有具体的对象
int[] li=(int[])method.invoke(null,"王五","man",25);
for(int i=0;i<li.length;i++){
System.out.println(li[i]);
}
}
/*
* 反射执行people的print(String name,String sex,int age)方法(private方法)
* */
@Test
public void test4() throws Exception{
Class<People> clazz1=People.class;
Method method=clazz1.getDeclaredMethod("getPersonalInfo", null);
method.setAccessible(true);
//调用静态方法可以不用有具体的对象
String[] li=(String[])method.invoke(new People(),null);
for(int i=0;i<li.length;i++){
System.out.println(li[i]);
}
}
</pre><pre name="code" class="java"><span style="white-space:pre"> </span>/**
* 通过反射执行main方法
*/
@Test
public void testMain() throws Exception{
Class clazz1 = MethodGetDemo.class;
Method method=clazz1.getMethod("main", String[].class);
method.invoke(null, new String[]{"w","z"});
}