Java反射调用方法

package com.lf.entity;

import com.lf.annotation.SetProperty;
import com.lf.annotation.SetTable;

public class UserEntity {
    private String userName;
    private int userAge;
    
    private final int money = 10000;
    
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public int getUserAge() {
        return userAge;
    }
    public void setUserAge(int userAge) {
        this.userAge = userAge;
    }
    //借钱方法
    public int getMoney(){
        System.out.println("你借了 " + money + "元!");
        return money;
    }
    //还钱方法,单个参数
    public void repay(int money){
        System.out.println("你还了 " + money + "元!");
    }
    //还钱方法,多个参数
    public void repay(String userName,int money){
        System.out.println(userName+ " 还了 " + money + "元!");
    }
}
public class ClassDemo02 {

     public static void main(String[] args) {
          Person p1 = new Person("小明" ,20,'男' );
          Person p2 = new Person("小红" ,23,'女' );

           //创建Class对象的方式一:(对象.getClass()),获取person类中的字节码文件
           Class class1 = p1.getClass();
          System. out.println(p1.getClass().getName());
           Class class2 = p2.getClass();
          System. out.println(class1 == class2 );

          System. out.println("==============================" );
           //创建Class对象的方式二:(类.class:需要输入一个明确的类,任意一个类型都有一个静态的class属性)
           Class class3 = Person.class;
          System. out.println(class1 == class2);

          System. out.println("==============================" );
           //创建Class对象的方式三:(forName():传入时只需要以字符串的方式传入即可)
           //通过Class类的一个forName(String className)静态方法返回一个Class对象,className必须是全路径名称;
           //Class.forName()有异常:ClassNotFoundException

           Class class4 = null;
           try {
              class4 = Class.forName("cn.itcast.Person");
          } catch (ClassNotFoundException e) {
               // TODO Auto-generated catch block
              e.printStackTrace();
          }
          System. out.println(class4 == class3);
     }
}
public class reflect03 {

    public static void main(String[] args) throws Exception {

        Class c1 = Class.forName("com.itheima04.Test_20171106.Test_20171207.Person");

        //创建此Class对象所表示类的一个新实例,
        //newInstance方法调用的是Person的空参数构造方法
        Object o = c1.newInstance();
        System.out.println(o.toString());
    }

你可能感兴趣的:(Java)