Java中的反射

反射

反射机制就是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。

反射的使用

反射创建对象

package com.westos.entities;

public class Product {
    private int id;
    private String name;
    private double price;

    public Product() {
    }

    public Product(int id, String name, double price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
    private void a(){
        System.out.println("aaa");
    }
}

方式1

 Class<?> c = Class.forName("com.westos.entities.Product");//得到类对象
Product o = (Product)c.newInstance();//创建新的实例对象

方式2

Class<?> p = Product.class;//类对象
Product product = (Product) p.newInstance();//创建新的实例对象

反射得到本类的方法,包括公有的和私有的

Class<?> c = Class.forName("com.westos.entities.Product");
        Method[] methods = c.getDeclaredMethods();
        for(Method method:methods)
            System.out.println(method);

反射得到本类及继承的所有公有方法    

 Class<?> c = Class.forName("com.westos.entities.Product");
        Method[] methods = c.getMethods();
        for(Method method:methods)
            System.out.println(method);

反射获取单个方发法 

Class<?> c = Class.forName("com.westos.entities.Product");
        Method setId = c.getMethod("setId",int.class);
        System.out.println(setId);

反射调动方法

 Class<?> c = Class.forName("com.westos.entities.Product");
        Product p = (Product)c.newInstance();
        Method a = c.getDeclaredMethod("a");
        a.setAccessible(true);
        System.out.println(a);
        a.invoke(p);

通过反射得到本类的私有和公有属性

Field[] fields = c.getDeclaredFields();

反射调用有参构造

Class<Product> c = Product.class;
        Constructor<Product> constructor = c.getConstructor(int.class, String.class, double.class);
        Product aa = constructor.newInstance(1, "aa", 12.3);
        System.out.println(aa);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值