Java笔记总结(五十四)---Java的反射机制

正常创建对象是new一个对象,反射是在引用的类无法满足现有需求的情况下,加载类,调用方法,创建对象 ,最大的作用是可以调用私有方法。

  • class类:代表java中的类或接口,通过class可以调用构造方法,类,方法等信息
  • constructor类:代表类的构造函数,通过constructor类,可以创建对象
  • method类:可以调用方法
  • field类:可以修改字段

class.forname(全限定名):怎么定义,路径的地址应该怎么写???路径中间是.(点)
获取全限定类名的方法:

Class c = refla.class;
String classname = c.getName();
System.out.println(classname);

Java反射常用到的方法:

1)获取类的三种方法:
通过类名.class获取
Class c = refla.class;
通过class.forname获取
Class c = Class.forName(“test.refla”);
通过对象.getclass获取
Class c = new refla().getClass();
2)获取方法:
getMethods 获取公共方法
getDeclaredMethods 获取所有非public的方法

	Method[] method1 = c.getMethods();
for(Method method:method1){
    System.out.println(method.getName());
}//输出public的方法信息

3)创建对象:
通过class对象的newInstance 创建对象
Class c = refla.class;
refla refla = (test.refla) c.newInstance();
通过 Constructor 对象的 newInstance() 方法
Class c = refla.class;
Constructor constructor = c.getConstructor();
refla refla = (test.refla) constructor.newInstance();
通过构造器可以调用有参构造函数

Class clz = Apple.class;
Constructor constructor = clz.getConstructor(String.class, int.class);
Apple apple = (Apple)constructor.newInstance("红富士", 15);
public class Apple {
    private int price;
    public int getPrice() {
        return price;
    }
    public void setPrice(int price) {
        this.price = price;
    }
    public static void main(String[] args) throws Exception{
        //正常的调用
        Apple apple = new Apple();
        apple.setPrice(5);
        System.out.println("Apple Price:" + apple.getPrice());
        //使用反射调用
        Class clz = Class.forName("com.chenshuyi.api.Apple");//获取类
        Method setPriceMethod = clz.getMethod("setPrice", int.class);//根据类获取方法,参数类型.class
        Constructor appleConstructor = clz.getConstructor();//获取构造器
        Object appleObj = appleConstructor.newInstance();//创建对象
        setPriceMethod.invoke(appleObj, 14);
        Method getPriceMethod = clz.getMethod("getPrice");
        System.out.println("Apple Price:" + getPriceMethod.invoke(appleObj));//invoke调用方法
    }
}

反射调用私有方法

package test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class refla {

    private double price;
    private void test(){
        System.out.println("测试价格");
    }

    public static void main(String[] args) throws Exception {
      Class c = Class.forName("test.refla");
        Method method = c.getDeclaredMethod("test");
//        Constructor constructor = c.getConstructor();
        Object o = c.newInstance();
        method.invoke(o);
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值