How to create an object from a string in Java (how to eval a string)?

前端 未结 7 1996
醉梦人生
醉梦人生 2020-12-03 13:08

I know eval is \"evil\", but I\'m using it in a way that the user can\'t ever abuse it.

Let\'s say I\'ve got a string \"new Integer(5)\". I want to do something suc

相关标签:
7条回答
  • 2020-12-03 14:00

    The Integer class takes a String in its constructor to set the value, assuming the provided string contains only numeric text.

    Integer foo;
    
    public void setFoo(String str) {
       if(isInt(str)) {
         foo = new Integer(str.trim());
       }
    }
    
    // Returns a boolean based on if the provided string contains only numbers
    private boolean isInt(String str) {
      boolean isInt = true;
    
      try {
        Integer.parseInt(str.trim());
      } catch (NumberFormatException nfe) {
        isInt = false;
      }
    
      return isInt;
    }
    
    // Get the value as an int rather than Integer
    public int getIntValue(String str) {
      return Integer.parseInt(str.trim());
    }
    
    0 讨论(0)
提交回复
热议问题