Struts2为父Action自动赋值

本文深入探讨了在使用Struts2框架进行项目开发时,如何通过继承ActionSupport并定义通用属性,以及如何利用Java反射技术从子类中获取父类的属性和方法,特别关注了如何通过父Action的public方法为属性赋值。

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

在使用Struts2框架做项目的时候,大多数情况下,我们都会定义一个Action继承ActionSupport作为我们的父Action。在父Action中我们会把通用的一些属性提出来,但是怎么为这些属性赋值呢?

1.先看一下利用java反射,我们能从子类中获取父类的哪些属性和方法。

/**
* 父类,分别定义了三种修饰符修饰的属性和方法
*/
public class Father {

private String name;

public String love;

protected String money;

private String getName() {
return this.name;
}

public String getLove() {
return this.love;
}

protected String getMoney() {
return this.money;
}

}


/**
* 子类,只继承父类
*/
public class Child extends Father {

}


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

/**
* 测试类
* 测试Child的getDeclaredMethods,getMethods能获取哪些Method
* 测试Child的getDeclaredFields,getFields能获取哪些Field
*/
public class Test {

public static void main(String[] args) {

// 输出""
{
Method[] methods = Child.class.getDeclaredMethods();

for (Method method : methods) {
System.out.println(method.getName());
}
}

System.out.println("-----------------------------------");

// 输出
// getLove
// wait
// wait
// wait
// equals
// toString
// hashCode
// getClass
// notify
// notifyAll
{
Method[] methods = Child.class.getMethods();

for (Method method : methods) {
System.out.println(method.getName());
}
}

System.out.println("-----------------------------------");

// 输出""
{
Field[] fields = Child.class.getDeclaredFields();

for (Field field : fields) {
System.out.println(field.getName());
}
}

System.out.println("-----------------------------------");

// 输出
// love
{
Field[] fields = Child.class.getFields();

for (Field field : fields) {
System.out.println(field.getName());
}
}

}

}

经过测试,用反射反射只能从子类中获取父类的public的属性和方法。

2.经测试在Struts2访问Action能通过父Action的public方法给属性赋值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值