【代码积累】replace constructor with factory

本文展示了一个使用Java实现的单例工厂模式示例代码,该工厂类利用`ConcurrentHashMap`来注册并管理对象实例。通过静态方法`getInstance()`获取工厂实例,并提供创建指定类型对象的方法`createSpecifiedVehicle()`。

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

import java.util.concurrent.ConcurrentHashMap;


public class Factory {
	private ConcurrentHashMap<String, Object> registedList = new ConcurrentHashMap<String, Object>();
	public void register(String name,Object object) {
		registedList.put(name, object);
	}
	
	private static Factory factory = null;
	
	public Vehicle createSpecifiedVehicle(String name) {
		return ((Vehicle)registedList.get(name)).createObject();
		/*This is not gonna work as when createSpecifiedVehicle is called the static blocks in sub-classes has not been 
		 * executed yet so registedList is actually empty.Static block in a class will be executed at the time the class
		 * is being load,and only when the class is needed it will be loaded by ClassLoader.*/
	}
	
	public static Factory getInstance() {
		if( null == factory ) {
			synchronized(Factory.class) {
				if( null == factory ) {
					factory = new Factory();
				}
			}
		}
		
		return factory;
	}
}

"no String-argument constructor/factory method to deserialize from String value"是表示无法从字符串值反序列化为对象的错误信息。这通常发生在使用Jackson或其他JSON解析库进行对象反序列化时,如果对象没有适当的构造函数或工厂方法来接受字符串参数。 为了解决这个问题,可以通过添加一个带有字符串参数的构造函数来手动赋值。例如,在引用中提到的解决办法中,通过添加一个带有json参数的构造函数来手动赋值。 另外,还需要确保对象的成员变量与JSON字符串中的键对应。如果JSON字符串中的键与对象的成员变量不匹配,也可能导致反序列化失败。 总之,要解决“no String-argument constructor/factory method to deserialize from String value”错误,可以通过添加适当的构造函数或工厂方法来接受字符串参数,并确保对象的成员变量与JSON字符串中的键对应。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [no String-argument constructor/factory method to deserialize from String val](https://blog.csdn.net/qq_30162239/article/details/86647164)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [项目debug|no String-argument constructor/factory method to deserialize from String val](https://blog.csdn.net/weixin_48118167/article/details/125890421)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值