有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java:如何从类型A转换为类型B?

我是一名java初学者,虽然我在这里和谷歌上都搜索过这个主题,但我还没有找到它。我肯定它一定在那里的某个地方,但是我不知道如何搜索。无论如何,这是:

如何编写方法将string/int/etc转换为类,反之亦然?我当然希望我的类转换是自动的,但我可以接受不太完美的类型转换。我不喜欢的是调用类(“某个字符串”)或类。toString()用于从字符串到类的来回转换。我希望它尽可能无缝。下面是一个例子:

我有一个IsFound类,它的行为类似于布尔值,我将它用作方法中的返回类型;在方法体中,我返回一个类似“found”的字符串(而不是true)。你可能会嘲笑我没有使用布尔值,但我想玩一点自定义类/类型。这里有一些代码

public class IsFound{

    public boolean found; // field

    public IsFound(String isFound_){
         if(isFound_.equals("FOUND")){
              found = true;
         else found = false;
         }
    }

    public String toString(){
    if(found)   return "found";
    else    return "not found";
    }    
}

这是我能做到的最远的了。我需要从字符串到字符串的转换方法,对于将来的参考,我想知道转换程序是否适用于int、char甚至其他类

扩展Boolean的解决方案只是作为最后一种手段,因为我不知道自己在进行什么扩展——我想自己从0创建类。 编辑: 我希望能够使用以下内容:

public IsFound parse(String substring_){
    if(search(substring_, string) == true){
        return FOUND; // or return "FOUND";
    {
    return NOTFOUND; // or return "NOT FOUND";
{

目前,它给出了无法从字符串转换为IsFound的错误。我想填补这个空白


共 (3) 个答案

  1. # 1 楼答案

    对于“字符串”表示和POJO(纯旧java对象)之间的转换,您可能希望使用序列化与JSON(或XML)等已知文本格式进行转换

    public class Search {
    
     private boolean found;
    
     // getters, setters, constructor
    
    }
    

    使用谷歌的GSON库进行序列化/反序列化:

    Search search = new Search();
    search.setFound(true);
    
    Gson gson = new Gson();
    String json = gson.toJson(search);
    // should output : { "found" : "true" } 
    
    // The opposite way , if json is a string equal to { "found" : "true" } 
    Gson gson = new Gson();
    Search s = gson.fromJson(json, Search.class);
    // s has found = true 
    
  2. # 2 楼答案

    我还将使用一个枚举,这里有一个枚举提供了类中的所有功能

      public enum IsFound{
        // each of these definitions are like calls to the IsFound constructor below
        FOUND("found"),
        NOT_FOUND("not found");
    
        // string representation
        private final String toString;
    
        private IsFound(String isFound){
          this.toString = isFound;
        }
    
        /**
         * @Override
         */
        public String toString(){
          return toString;
        }    
    
    
        // I think this is what you want. I'm not sure why you need this, but
        // am including it as I think it gives you what you want. see example below
        public static IsFound convert( String foundString ){
          if( FOUND.toString.equals(foundString) ){
            return FOUND;
          }
          else if( NOT_FOUND.toString.equals(foundString) ){
            return NOT_FOUND;
          }
          else{
            return null;
          }
        }
      }
    

    您可以通过以下方式使用它:

    private IsFound myFoundValue;
    
    myFoundValue = IsFound.FOUND;
    
    System.out.println(myFoundValue.toString()); // "found"
    
    myFoundValue = IsFound.NOT_FOUND;
    
    System.out.println(myFoundValue.toString()); // "not found"
    
    switch( myFoundValue ){
      case FOUND:
        System.out.println("the value is FOUND");
      break;
      case NOT_FOUND:
        System.out.println("the value is NOT_FOUND");
      break;
      default:
        System.out.println("this should never happen");
      break;
    }
    
    myFoundValue = IsFound.convert("found"); // IsFound.FOUND
    
    System.out.println( myFoundValue.toString() ); // "found"
    
  3. # 3 楼答案

    你的问题闻起来像是一个经典的XY Problem问题,因为你似乎找错了方向,想找到一个你可能需要更好理解的问题的解决方案。尝试使用字符串代替类型是一种反模式,所以最好不要这样做。对于这样的情况,考虑使用布尔型为两态类型或多状态类型的枚举。

    例如

    public enum IsFound{
      FOUND, NOT_FOUND, UNKNOWN
    }
    

    或者

    public enum IsFound {
       FOUND("Found"), NOT_FOUND("Not Found"), UNKNOWN("Unknown");
    
       private String name;
    
       private IsFound(String name) {
          this.name = name;
       }
    
       public String getName() {
          return name;
       }
    
       @Override
       public String toString() {
          return name;
       }
    
    }
    

    在别的班

    private Map<Luggage, IsFound> lostLuggageMap = new HashMap<>();
    
    • 枚举添加了一个编译时类型安全性,而字符串没有
    • 枚举可以具有非常有用的属性和行为(方法)