java---反射

java—反射
反射机制调用方法:
1、获取对象,直接通过对象调用方法
2、第二种方法,通过方法名获取方法,执行方法
反射demo实体

package com.example.demo.reflection.bean;

/**
 * @ Author     :lzy
 * @ Date       :Created in  2019/8/14 15:59
 * @ Description:
 */
public class TestBean {

    public String string;

    public String getString(String str){
        return str+str;
    }
    public String getStr2(String str){
        return str+str;
    }
}

反射

package com.example.demo.reflection;

import com.example.demo.reflection.bean.TestBean;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

  package com.example.demo.reflection;

import com.example.demo.reflection.bean.TestBean;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @ Author     :lzy
 * @ Date       :Created in  2019/8/14 15:59
 * @ Description:
 */
public class TestDemo {
    public static void main(String[] args) {
        //获取属性值
        Class cls= TestBean.class;
        Field[] declaredFields = cls.getDeclaredFields();
        for (Field fiels:declaredFields
             ) {
            System.out.println("获取对象属性"+fiels.getName());
        }

        TestBean testBean = new TestBean();
        Class cls1 = null;
        try {
            cls1=Class.forName("com.example.demo.reflection.bean.TestBean");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        Method method=null;
        try {
            method=cls1.getMethod("getString",String.class);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        Object invoke=null;
        try {
            //获取方法调用
            invoke= method.invoke(testBean, "123");
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        System.out.println("反射方法获取:"+invoke);
        TestBean testBean1=null;
        try {
            testBean1 = (TestBean) cls1.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        String string = testBean1.getString("123");
        System.out.println("反射实体类获取:"+string);

        }
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值