简单的反射

本文通过一个具体的Java程序示例介绍了如何使用Java反射机制来获取并操作类的对象属性。示例中定义了一个简单的Java Bean,并利用反射来读取Bean中的属性值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class ds
{
    private String name;
    private String age;
    private String sex;
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public String getAge()
    {
        return age;
    }
    public void setAge(String age)
    {
        this.age = age;
    }
    public String getSex()
    {
        return sex;
    }
    public void setSex(String sex)
    {
        this.sex = sex;
    }

}

 

 

 

 

package matck.ma;

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

public class invort
{

    /**
     * <[Description]>
     * @param args
     * @author yKF51945
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     */
    public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException
    {
        ds sc = new ds();
        sc.setName("hello");
        sc.setAge("18");
        sc.setSex("man");
        vort(sc);

    }
   
    public static void vort(ds sc) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException
    {
        String filed ="";
       
        Class<?> beanclass =  sc.getClass();
       
        Method[]  methods =   beanclass.getMethods();
       
        for(Method md :methods)
        {
           if( md.getName().equals("getName"))
           {
               filed =  (String) md.invoke(sc);
               if("hello".equals(filed))
               {
                   System.out.println(filed);
               }
           }
           
        }
   }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值