JAVA反射小例子

本文通过一个具体的Java程序示例,详细介绍了如何使用Java反射机制来动态创建和操作对象。主要涵盖了如何利用反射获取类实例、获取类声明的所有字段、设置字段值及调用方法等内容。

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


package com.xhj.test;

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

public class TestReflect
{
public static void main(String[] args)
{
try
{
Class clazz = Class.forName("com.xhj.test.Person");
Object obj = clazz.newInstance();

Field[] fields = clazz.getDeclaredFields();
for (Field field : fields)
{
String fieldName = field.getName();
//System.out.println("fieldName : " + fieldName);

String firstUp = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
//System.out.println("firstUp : " + firstUp);

try
{
Method method = clazz.getMethod("set" + firstUp, new Class[]{field.getType()});
if ("String".equals(field.getType().getSimpleName()))
{
method.invoke(obj, new Object[]{"xhj"});
}
else if ("int".equals(field.getType().getSimpleName()))
{
method.invoke(obj, new Object[]{26});
}

Method getMethod = clazz.getMethod("get" + firstUp, new Class[]{});
getMethod.invoke(obj, null);
}
catch (NoSuchMethodException e)
{
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InvocationTargetException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InstantiationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalAccessException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SecurityException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


class Person
{
String name;
int age;

public Person()
{

}

public String getName()
{
System.out.println(name);
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
System.out.println(age);
return age;
}
public void setAge(int age)
{
this.age = age;
}
}


getFields:获得所有公共字段
getDeclaredFields:获取声明的所有字段,包括公共、保护、默认(包)访问和私有字段,但不包括继承的字段
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值