Java枚举嵌入在字段中。

huangapple go评论76阅读模式
英文:

Java Enum embed the class in the feild

问题

public enum Country {
	
	AFGHANISTAN("Afghanistan", "AF", "AFG", 004, RegionAfghanistan.class),
	ALBANIA("Albania", "AL", "ALB", 8, RegionAlbania.class);
    // Other enum values and methods.
}
public enum RegionAfghanistan {

	BADAKHSHAN("Badakhshān", "AF-BDS*", CountryCategory.PROVINCE),
	BAGHLAN("Baghlān", "AF-BGL*", CountryCategory.PROVINCE),
	BALKH("Balkh", "AF-BAL*", CountryCategory.PROVINCE),
	BADGHIS("Bādghīs", "AF-BDG*", CountryCategory.PROVINCE),
	BAMYAN("Bāmyān", "AF-BAM*", CountryCategory.PROVINCE),
	DAYKUNDI("Dāykundī", "AF-DAY*", CountryCategory.PROVINCE),
    // Other enum values and methods.
}
Class c = Country.AFGHANISTAN.getRegion();
Method methodname = c.getMethod("valueOf", String.class);
Object result = methodname.invoke(null, "BADAKHSHAN");
System.out.println(result); 

The code you provided is mostly correct. However, there's a small change needed when invoking the method to get the RegionAfghanistan enum value by its name. You should use the valueOf method to achieve this. The modified code snippet above demonstrates how to do it.

In this code, you first obtain the RegionAfghanistan class from the Country.AFGHANISTAN enum, then you use the getMethod to get the valueOf method by name. Finally, you invoke this method with the enum value name (in this case, "BADAKHSHAN") to obtain the corresponding RegionAfghanistan enum value.

英文:

I have one java enum class called Country for which I have below code :

public enum Country {
	
	AFGHANISTAN("Afghanistan","AF","AFG",004, RegionAfghanistan.class),
	ALBANIA("Albania","AL","ALB",8, RegionAlbania.class);
    .......
    Some methods and constructor.
}

So you can see in the last field I have embedded the class in the enum fields. Each of these region is enum class as below.

public enum RegionAfghanistan {

	BADAKHSHAN("Badakhshān", "AF-BDS*", CountryCategory.PROVINCE),
	BAGHLAN("Baghlān", "AF-BGL*", CountryCategory.PROVINCE),
	BALKH("Balkh", "AF-BAL*", CountryCategory.PROVINCE),
	BADGHIS("Bādghīs", "AF-BDG*", CountryCategory.PROVINCE),
	BAMYAN("Bāmyān", "AF-BAM*", CountryCategory.PROVINCE),
	DAYKUNDI("Dāykundī", "AF-DAY*", CountryCategory.PROVINCE),
    ......
    Some methods and feilds.

Now Suppose I am given Region: Badakhshān Country: Afghanistan as a String. First I have method which gives me Country.AFGHANISTAN from the "Afghanistan", So that, is fine.
I also get a class from the Country.AFGHANISTAN i.e. class com.****.core.location.RegionAfghanistan but I would like to get RegionAfghanistan.BADAKHSHAN from the given region "Badakhshān".
Could you please help me how to achieve this using the java enums. Hope you understand what I want to achieve using this.

I have used the following code

Class c = Country.AFGHANISTAN.getRegion(); 
Method methodname = c.getMethod("getRegionAfghanistanBySubdivisionName", String.class); 
System.out.println(methodname.invoke(c, "Badakhshān")); 

I get Country.AFGHANISTAN from string "Afghanistan", then I get the class and I invoke a method in class passing the region "Badakhshān" and I get the right value but I am not sure if I am doing it the right way or there is another better way to do it.

I would really want a help if this is right approach or there is better way to do it....Thank you so much for your help.

答案1

得分: 2

public static RegionAfghanistan getByName(String name) {
for (RegionAfghanistan value : values()) {
if (value.name.equals(name)) {
return value;
}
}
throw new IllegalArgumentException("Not a region: " + name);
}

You can call this method via reflection given the Class object for RegionAfghanistan:

Class<RegionAfghanistan> regionAfghanistanClass = RegionAfghanistan.class;

// Look up method
Method getByName = regionAfghanistanClass.getMethod("getByName", String.class);

// Call it. It's a static method, so pass in "null"
RegionAfghanistan badakhshān = (RegionAfghanistan) getByName.invoke(null, "Badakhshān");
英文:

You could add a method to the RegionAfghanistan (and other region enumerations) that lets you look up a region by its name. It could look like:

    public static RegionAfghanistan getByName(String name) {
        for (RegionAfghanistan value : values()) {
            if (value.name.equals(name)) {
                return value;
            }
        }
        throw new IllegalArgumentException(&quot;Not a region: &quot; + name);
    }

You can call this method via reflection given the Class object for RegionAfghanistan:

Class&lt;RegionAfghanistan&gt; regionAfghanistanClass = RegionAfghanistan.class;

// Look up method
Method getByName = regionAfghanistanClass.getMethod(&quot;getByName&quot;, String.class);

// Call it. It&#39;s a static method, so pass in &quot;null&quot;
RegionAfghanistan badakhshān = (RegionAfghanistan) getByName.invoke(null, &quot;Badakhshān&quot;);

答案2

得分: 2

Here is the translated code section:

另一种方法是将国家枚举与其地区值关联起来,您需要改进 getRegions 调用以匹配文本标签,而不是我使用的 toUpperCase:

public enum RegionAfghanistan {
    BALKH, BAGHLAN;
}
public enum RegionUK {
    WALES, ENGLAND;
}
public enum Country {
    AFGHANISTAN(RegionAfghanistan.values()),
    UK(RegionUK.values());

    private Enum<?>[] regions;
    <T extends Enum<T>> Country(T[] values) {
        this.regions = values;
    }
    <T extends Enum<T>> T getRegion(String name) {
        return Enum.valueOf((Class<T>) regions[0].getClass(), name.toUpperCase());
    }
}
public static void main(String[] args) {
    System.out.println(Country.AFGHANISTAN.getRegion("Balkh"));
    System.out.println(Country.UK.getRegion("Wales"));
}

Please note that I have retained the original code structure and formatting while providing the translated code.

英文:

Another approach which links country enum to its regions values, you would need to improve getRegions call to match on the text labels rather than toUpperCase I used:

public enum RegionAfghanistan {
    BALKH, BAGHLAN;
}
public enum RegionUK {
    WALES, ENGLAND;
}
public enum Country {
    AFGHANISTAN(RegionAfghanistan.values()),
    UK(RegionUK.values());

    private Enum&lt;?&gt;[] regions;
    &lt;T extends Enum&lt;T&gt;&gt; Country(T[] values) {
        this.regions = values;
    }
    &lt;T extends Enum&lt;T&gt;&gt; T getRegion(String name) {
        return Enum.valueOf((Class&lt;T&gt;) regions[0].getClass(), name.toUpperCase());
    }
}
public static void main(String[] args) {
    System.out.println(Country.AFGHANISTAN.getRegion(&quot;Balkh&quot;));
    System.out.println(Country.UK.getRegion(&quot;Wales&quot;));
}

答案3

得分: 1

Experimented a bit, and figured out you can also do it by using a Region interface and an abstract method in the Country enum. This setup requires a lot of repeated code to tell it which Region enum to use though.

Region interface:

public interface Region{}

RegionUSA Enum:

public enum RegionUSA implements Region
{
  WASHINGTON, FLORIDA;
}

RegionCanada Enum:

public enum RegionCanada implements Region
{
  QUEBEC, ALBERTA;
}

RegionFrance Enum:

public enum RegionFrance implements Region
{
  NORMANDY, BERRY;
}

Country Enum:

public enum Country
{
  USA
  {
    @Override
    public Region getRegion(String region)
    {
      return RegionUSA.valueOf(region.toUpperCase());
    }
  }, 
  CANADA
  {
    @Override
    public Region getRegion(String region)
    {
      return RegionCanada.valueOf(region.toUpperCase());
    }
  }, 
  FRANCE
  {
    @Override
    public Region getRegion(String region)
    {
      return RegionFrance.valueOf(region.toUpperCase());
    }
  };
  
  public abstract Region getRegion(String region);
}

Main Class:

public class TestEnums
{
  public static void main(String[] args) 
  {
    System.out.println(Country.CANADA.getRegion("Alberta"));
    System.out.println(Country.USA.getRegion("Washington"));
    System.out.println(Country.FRANCE.getRegion("Normandy"));
  }
}
英文:

Experimented a bit, and figured out you can also do it by using a Region interface and a abtract method in the Country enum. This setup requires a lot of repeated code to tell it which Region enum to use though.

Region interface:

public interface Region{}

RegionUSA Enum:

public enum RegionUSA implements Region
{
  WASHINGTON, FLORIDA;
}

RegionCanada Enum:

public enum RegionCanada implements Region
{
  QUEBEC, ALBERTA;
}

RegionFrance Enum:

public enum RegionFrance implements Region
{
  NORMANDY, BERRY;
}

Country Enum:

public enum Country
{
  USA
  {
    @Override
    public Region getRegion(String region)
    {
      return RegionUSA.valueOf(region.toUpperCase());
    }
  }, 
  CANADA
  {
    @Override
    public Region getRegion(String region)
    {
      return RegionCanada.valueOf(region.toUpperCase());
    }
  }, 
  FRANCE
  {
    @Override
    public Region getRegion(String region)
    {
      return RegionFrance.valueOf(region.toUpperCase());
    }
  };
  
  public abstract Region getRegion(String region);
}

Main Class:

public class TestEnums
{
  public static void main(String[] args) 
  {
    System.out.println(Country.CANADA.getRegion(&quot;Alberta&quot;));
    System.out.println(Country.USA.getRegion(&quot;Washington&quot;));
    System.out.println(Country.FRANCE.getRegion(&quot;Normandy&quot;));
  }
}

huangapple
  • 本文由 发表于 2020年8月12日 23:06:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/63379407.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定