java175-method类反射机制

2022/7/6 14:25:35

本文主要是介绍java175-method类反射机制,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

//class反射编程
//定义一个学生类
public class test124 {
    public String name;
    protected int age;
 
    double height;
    private double money;
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getName() {
        return name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public test124(String name, Integer age){
        this.name=name;
        this.age=age;
        System.out.println( "调用有参构造方法" );
    }
 
    public test124(String name,int age,double money){
        this.name=name;
        this.age=age;
        this.money=money;
    }
    //看书
    public void learn(BookRead book){
        System.out.println( "我的名字"+name+ "我正在学习"+book.getName());
    }
    //奔跑
    public void run(){
        System.out.println( "我们喜欢奔跑" );
    }
}
定义一个method类

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
 
//method类反射机制
public class test129 {
    public static void main(String[] args){
        try {
            Class<?> stuCla = Class.forName( "test124" );
            test124 stuObj=new test124( "geyao",12 );
            BookRead book=new BookRead();
            book.setName( "歌谣" );
            Method learnMet=stuCla.getMethod( "learn", BookRead.class);
            learnMet.invoke( stuObj,book );
            //获取非公共方法
 
            Method runMet=stuCla.getDeclaredMethod( "run");
            if(!runMet.isAccessible()){
                runMet.setAccessible( true );
                runMet.invoke( stuObj );
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
定义一个bookread类

public class BookRead {
    private String name;
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getName() {
        return name;
    }
}
运行结果

 



这篇关于java175-method类反射机制的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程