Java根据Bean实体某一属性获取Bean全部信息
业务场景
业务涉及到多个国家,现在需要根据国家的某一属性(以国家简称为例)获得国家的全部信息。
业务代码
package com.example.country;
import lombok.*;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@ToString
public class CountryEnvironment {
@Getter
private final Integer countryNumber;//国家编码
@Getter
private final String countryName;//国家名称
@Getter
private final String countryLocation;//国家位置
@Getter
private final String countryAbbreviation;//国家简称
private CountryEnvironment(Integer countryNumber, String countryName, String countryLocation, String countryAbbreviation) {
this.countryNumber = countryNumber;
this.countryName = countryName;
this.countryLocation = countryLocation;
this.countryAbbreviation = countryAbbreviation;
}
private static final Map<String,CountryEnvironment> map = new ConcurrentHashMap<>();
public static CountryEnvironment getCountryInformation(String countryAbbreviation) {
if (map.get(countryAbbreviation) == null) {
CountryEnvironment countryEnvironment;
switch (countryAbbreviation) {
case "UK":
countryEnvironment = new CountryEnvironment(22, "Britain", "Southern", "UK");
break;
case "FR":
countryEnvironment = new CountryEnvironment(33, "France", "Northern", "FR");
break;
default:
throw new RuntimeException();
}
map.put(countryAbbreviation, countryEnvironment);
}
return map.get(countryAbbreviation);
}
public static void main(String[] args) {
//主函数测试
CountryEnvironment countryEnvironment = getCountryInformation("UK");
System.out.println(countryEnvironment);
}
}
测试结果:

该代码示例展示了一个Java类`CountryEnvironment`,包含国家的编码、名称、位置和简称等属性。类中使用一个ConcurrentHashMap存储基于国家简称的CountryEnvironment实例。静态方法`getCountryInformation`根据国家简称返回对应的CountryEnvironment对象。在主函数中,通过调用此方法测试了查询过程。
1496

被折叠的 条评论
为什么被折叠?



