javabean之PropertyEditorSupport

本文通过一个具体的示例介绍了如何使用Java的PropertyEditorSupport类实现字符串到自定义对象的转换。示例中创建了一个User类,并通过正则表达式解析特定格式的字符串来实例化User对象。
摘要由CSDN通过智能技术生成

PropertyEditorSupport像是一个从String到l类的转换器。

package com.beans;

import java.beans.PropertyEditorSupport;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import junit.framework.TestCase;

public class TestPropertyEditorSupport extends TestCase {

	public void testPropertyEditorSupport() {
		PropertyEditorSupport support = new UserPropertyEditorSupport();
		support.setAsText("User [age=18, name=yang]");
		System.out.println(support.getValue());
	}

	static class User {
		private int age;
		private String name;

		public User() {
			super();
		}

		public User(int age, String name) {
			this.age = age;
			this.name = name;
		}

		public int getAge() {
			return age;
		}

		public void setAge(int age) {
			this.age = age;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}
	}

	static class UserPropertyEditorSupport extends PropertyEditorSupport {
		private static final Pattern pattern = Pattern.compile("User \\[age=(\\d+), name=(\\S+)\\]");

		@Override
		public void setAsText(String text) throws IllegalArgumentException {
			if (text == null) {
				return;
			}
			Matcher matcher = pattern.matcher(text);
			if (matcher.matches()) {
				int age = Integer.parseInt(matcher.group(1));
				String name = matcher.group(2);

				User user = new User(age, name);
				setValue(user);
			}
		}

	}
}

运行,输出:

com.beans.TestPropertyEditorSupport$User@3b8b49


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值