作者:春哥在奋斗_ | 来源:互联网 | 2023-07-17 18:06
流程:我们新建一个Person借口,Chinese去实现Person借口,然而Person中有属性为ArrayList<Properties&
流程:我们新建一个Person借口,Chinese去实现Person借口,然而Person中有属性为ArrayList
的方法,Properties记录该人的一些属性,此处这样用ArrayList并不一定恰当,只是为了举例子而已:1.Person.java
package study;
public interface Person {
public void output();
}
2.Properties.java
package study;
public class Properties {
private float height;
private int age;
private String favor;
public float getHeight() {
return height;
}
public void setHeight(float height) {
this.height = height;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFavor() {
return favor;
}
public void setFavor(String favor) {
this.favor = favor;
}
}
3.Chinese.java
package study;
import java.util.ArrayList;
import java.util.List;
public class Chinese implements Person {
private List<Properties> properties = new ArrayList<Properties>();
private String name;
/**
* 构造方法
*/
public Chinese() {
System.out.println("Chinese类的构造函数,实例化...");
}
/**
* name的必须的setter方法
* @ 姓名
*/
public void setName(String name) {
this.name = name;
}
/**
* properties必须的setter方法
* @ 属性
*/
public void setProperties(List<Properties> l) {
this.properties = l;
}
@Override
public void output() {
// TODO Auto-generated method stub
System.out.println("姓名:" + this.name);
for (int i = 0; i < properties.size(); i++) {
System.out.println("身高:" + properties.get(i).getHeight());
System.out.println("年龄:" + properties.get(i).getAge());
System.out.println("爱好:" + properties.get(i).getFavor());
}
}
}
4.配置文件bean2.xml
"http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
id="chinese" class="study.Chinese">
name="name">
<value>zmpvalue>
name="properties">
class="study.Properties">
name="height">
<value>183value>
name="age">
<value>23value>
name="favor">
<value>运动,读书,写作value>
class="study.Properties">
name="height">
<value>154.3value>
name="age">
<value>18value>
name="favor">
<value>关于装逼的视野value>
5.测试类TestPerson.java
package study;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestPerson {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean2.xml");
Person p = (Person) ctx.getBean("chinese");
p.output();
}
}
6.运行结果:
来自为知笔记(Wiz)