001 /*
002 * PropertyEditorUtil.java
003 *
004 * Created on August 16, 2006, 7:09 PM
005 *
006 * To change this template, choose Tools | Template Manager
007 * and open the template in the editor.
008 */
009
010 package org.jdesktop.swingx.editors;
011
012 import java.lang.reflect.Constructor;
013 import java.lang.reflect.InvocationTargetException;
014
015 /**
016 *
017 * @author joshy
018 */
019 public class PropertyEditorUtil {
020 //the text could be in many different formats. All of the supported formats are as follows:
021 //(where x and y are doubles of some form)
022 //[x,y]
023 //[x y]
024 //x,y]
025 //[x,y
026 //[ x , y ] or any other arbitrary whitespace
027 // x , y ] or any other arbitrary whitespace
028 //[ x , y or any other arbitrary whitespace
029 //x,y
030 // x , y (or any other arbitrary whitespace)
031 //x y
032 // (empty space)
033 //null
034 //[]
035 //[ ]
036 //any other value throws an IllegalArgumentException
037 public static Object createValueFromString(String text, int count, Class objectClass, Class paramClass) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
038 // strip all extra whitespace
039 text = text.replaceAll("[\\[|,| |\\]]"," ");
040 text = text.replaceAll("\\s+"," ");
041 text = text.trim();
042 // u.p("text = " + text);
043 if (text == null || text.equals("") || text.equals("null")) {
044 return null;
045 }
046 // split by spaces
047 String[] strs = text.split(" ");
048 // u.p("split:");
049 // u.p(strs);
050 // u.p("len = " + strs.length);
051 if(strs.length != count) {
052 return null;
053 }
054 Object[] params = new Object[count];
055 Class[] paramClasses = new Class[count];
056 for(int i=0; i<strs.length; i++) {
057 if(paramClass == int.class) {
058 params[i] = Integer.valueOf(strs[i]);
059 paramClasses[i] = paramClass;
060 }
061 if(paramClass == double.class) {
062 params[i] = Double.valueOf(strs[i]);
063 paramClasses[i] = paramClass;
064 }
065 }
066 // u.p("parms = ");
067 // u.p(params);
068 Constructor con = objectClass.getConstructor(paramClasses);
069 return con.newInstance(params);
070 }
071
072 }