1 19 20 package org.netbeans.modules.convertor; 21 22 import java.lang.reflect.Constructor ; 23 import java.lang.reflect.Method ; 24 import java.util.Properties ; 25 import org.netbeans.api.convertor.ConvertorException; 26 import org.openide.ErrorManager; 27 import org.openide.util.Lookup; 28 import org.openide.util.Utilities; 29 30 34 public class InstanceUtils { 35 36 private InstanceUtils() { 37 } 38 39 public static Object newValue(String val, Properties properties) { 40 val = Utilities.translate(val); 41 try { 42 Class c = findClass(val); 43 if (properties == null) { 44 return c.newInstance(); 45 } else { 46 Constructor con = c.getConstructor(new Class []{Properties .class}); 47 return con.newInstance(new Object []{properties}); 48 } 49 } catch (Exception e) { 50 ConvertorException e2 = new ConvertorException("Cannot instantiate class "+val); ErrorManager.getDefault().annotate(e2, e); 52 throw e2; 53 } 54 } 55 56 public static Object methodValue(String val, Properties properties) { 57 int sepIdx = val.lastIndexOf('.'); 58 if (sepIdx == -1) { 59 throw new ConvertorException("Cannot call method "+val+", because it is not fully qualified."); } 61 62 String methodName = val.substring(sepIdx+1); 63 String className = val.substring(0,sepIdx); 64 65 try { 66 Class cls = findClass(className); 67 if (properties == null) { 68 Method method = cls.getMethod(methodName, new Class []{}); 69 return method.invoke(null, new Object []{}); 70 } else { 71 Method method = cls.getMethod(methodName, new Class []{Properties .class}); 72 return method.invoke(null, new Object []{properties}); 73 } 74 } catch (Exception e) { 75 ConvertorException e2 = new ConvertorException("Cannot instantiate method "+val); ErrorManager.getDefault().annotate(e2, e); 77 throw e2; 78 } 79 } 80 81 public static Class findClass(String name) throws ClassNotFoundException { 82 ClassLoader c = (ClassLoader )Lookup.getDefault().lookup(ClassLoader .class); 83 if (c == null) { 84 return Class.forName(name, true, null); 85 } else { 86 return Class.forName(name, true, c); 87 } 88 } 89 90 91 } 92 | Popular Tags |