Java tutorial
//package com.java2s; /* * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import org.json.JSONArray; import org.json.JSONException; import javax.annotation.Nullable; import java.util.HashSet; import java.util.Set; public class Main { @Nullable public static Object valueFromString(String newValue, Object existingValue) throws IllegalArgumentException { if (existingValue instanceof Integer) { return Integer.parseInt(newValue); } else if (existingValue instanceof Long) { return Long.parseLong(newValue); } else if (existingValue instanceof Float) { return Float.parseFloat(newValue); } else if (existingValue instanceof Boolean) { return parseBoolean(newValue); } else if (existingValue instanceof String) { return newValue; } else if (existingValue instanceof Set) { try { JSONArray obj = new JSONArray(newValue); int objN = obj.length(); HashSet<String> set = new HashSet<String>(objN); for (int i = 0; i < objN; i++) { set.add(obj.getString(i)); } return set; } catch (JSONException e) { throw new IllegalArgumentException(e); } } else { throw new IllegalArgumentException("Unsupported type: " + existingValue.getClass().getName()); } } private static Boolean parseBoolean(String s) throws IllegalArgumentException { if ("1".equals(s) || "true".equalsIgnoreCase(s)) { return Boolean.TRUE; } else if ("0".equals(s) || "false".equalsIgnoreCase(s)) { return Boolean.FALSE; } throw new IllegalArgumentException("Expected boolean, got " + s); } }