/** * Set the object to be edited. * * @param value The object to be edited. */ public void setObject(Object value) { if (!(_type.isInstance(value))) { throw new IllegalArgumentException(value.getClass() + " is not of type " + _type); } _value = value; // Disable event generation. _squelchChangeEvents = true; // Iterate over each property, doing a lookup on the associated editor // and setting the editor's value to the value of the property. Iterator it = _prop2Editor.keySet().iterator(); while (it.hasNext()) { PropertyDescriptor desc = (PropertyDescriptor) it.next(); PropertyEditor editor = (PropertyEditor) _prop2Editor.get(desc); Method reader = desc.getReadMethod(); if (reader != null) { try { Object val = reader.invoke(_value, null); editor.setValue(val); } catch (IllegalAccessException ex) { ex.printStackTrace(); } catch (InvocationTargetException ex) { ex.getTargetException().printStackTrace(); } } } // Enable event generation. _squelchChangeEvents = false; }
/** * Insert the source code details, if available. * * @param ped The given program element. */ public void addSourcePosition(ProgramElementDoc ped, int indent) { if (!addSrcInfo) return; if (JDiff.javaVersion.startsWith("1.1") || JDiff.javaVersion.startsWith("1.2") || JDiff.javaVersion.startsWith("1.3")) { return; // position() only appeared in J2SE1.4 } try { // Could cache the method for improved performance Class c = ProgramElementDoc.class; Method m = c.getMethod("position", null); Object sp = m.invoke(ped, null); if (sp != null) { for (int i = 0; i < indent; i++) outputFile.print(" "); outputFile.println("src=\"" + sp + "\""); } } catch (NoSuchMethodException e2) { System.err.println("Error: method \"position\" not found"); e2.printStackTrace(); } catch (IllegalAccessException e4) { System.err.println("Error: class not permitted to be instantiated"); e4.printStackTrace(); } catch (InvocationTargetException e5) { System.err.println("Error: method \"position\" could not be invoked"); e5.printStackTrace(); } catch (Exception e6) { System.err.println("Error: "); e6.printStackTrace(); } }
public static final void fireEvent(GenericEvent e, Method m, Vector listeners) throws PropertyVetoException { Object[] snapshot = null; synchronized (listeners) { snapshot = new Object[listeners.size()]; listeners.copyInto(snapshot); } // leighd 04/14/99 - modified for event debugging if (gDebugEvents) Engine.debugLog("Event : " + e.toString()); Object params[] = new Object[] {e}; for (int i = 0; i < snapshot.length; i++) { if ((e instanceof Consumable) && ((Consumable) e).isConsumed()) { // leighd 04/14/99 // note that we don't catch the consumption of the // event until we've passed through the loop again, // so we reference i-1 if (gDebugEvents) Engine.debugLog("Consumed By : " + snapshot[i - 1]); return; } try { m.invoke(snapshot[i], params); } catch (IllegalAccessException iae) { iae.printStackTrace(); } catch (InvocationTargetException ite) { Throwable t = ite.getTargetException(); if (t instanceof PropertyVetoException) throw ((PropertyVetoException) t); else t.printStackTrace(); } } }
public Matrix createVector(BitVector selector) { int rows = selector != null ? selector.countOnBits() : frame.size(); Matrix m = new Matrix(rows, 1); for (int i = 0, j = 0; j < frame.size(); j++) { if (selector == null || selector.isOn(j)) { M rowValue = frame.object(j); try { Number numValue = (Number) numericField.get(rowValue); m.set(i, 0, numValue.doubleValue()); } catch (IllegalAccessException e) { e.printStackTrace(); throw new IllegalStateException( String.format( "Couldn't access field %s: %s", numericField.getName(), e.getMessage())); } i++; } } return m; }
private void bindDataSource( Component componentRoot, Object controller, Method method, UiDataSource dataSource) { String componentId = dataSource.value(); Component component = Clara.findComponentById(componentRoot, componentId); Class<?> dataSourceClass = method.getReturnType(); try { // Vaadin data model consists of Property/Item/Container // objects and each of them have a Viewer interface. if (isContainer(dataSourceClass) && component instanceof Container.Viewer) { ((Container.Viewer) component) .setContainerDataSource((Container) method.invoke(controller)); } else if (isProperty(dataSourceClass) && component instanceof Property.Viewer) { ((Property.Viewer) component).setPropertyDataSource((Property) method.invoke(controller)); } else if (isItem(dataSourceClass) && component instanceof Item.Viewer) { ((Item.Viewer) component).setItemDataSource((Item) method.invoke(controller)); } // TODO exception handling } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } }
/** * Creates a new entity enumeration icon chooser. * * @param enumeration the enumeration to display in this combo box */ public EnumerationIconChooser(Class<E> enumeration) { super(); this.enumeration = enumeration; try { this.icons = (ImageIcon[]) enumeration.getMethod("getIcons").invoke(null); for (int i = 0; i < icons.length; i++) { addItem(icons[i]); } } catch (NoSuchMethodException ex) { System.err.println( "The method 'getIcons()' is missing in enumeration " + enumeration.getName()); ex.printStackTrace(); System.exit(1); } catch (IllegalAccessException ex) { System.err.println( "Cannot access method 'getIcons()' in enumeration " + enumeration.getName() + ": ex.getMessage()"); ex.printStackTrace(); System.exit(1); } catch (InvocationTargetException ex) { ex.getCause().printStackTrace(); System.exit(1); } }
/** evaluate the link function */ public static Data link(VMethod m, Object[] o) throws VisADException { Data ans = null; if (o != null) { for (int i = 0; i < o.length; i++) { // convert VRealTypes to RealTypes if (o[i] instanceof VRealType) { o[i] = ((VRealType) o[i]).getRealType(); } } } try { ans = (Data) FormulaUtil.invokeMethod(m.getMethod(), o); } catch (ClassCastException exc) { if (FormulaVar.DEBUG) exc.printStackTrace(); throw new VisADException("Link error: invalid linked method"); } catch (IllegalAccessException exc) { if (FormulaVar.DEBUG) exc.printStackTrace(); throw new VisADException("Link error: cannot access linked method"); } catch (IllegalArgumentException exc) { if (FormulaVar.DEBUG) exc.printStackTrace(); throw new VisADException("Link error: bad method argument"); } catch (InvocationTargetException exc) { if (FormulaVar.DEBUG) exc.getTargetException().printStackTrace(); throw new VisADException("Link error: linked method threw an exception"); } if (ans == null) { throw new VisADException("Link error: linked method returned null data"); } return ans; }
private void bindEventHandler( Component componentRoot, Object controller, Method method, UiHandler eventListener) { String componentId = eventListener.value(); Component component = Clara.findComponentById(componentRoot, componentId); if (component == null) { throw new BinderException("No component found for id: " + componentId + "."); } Class<?> eventType = (method.getParameterTypes().length > 0 ? method.getParameterTypes()[0] : null); if (eventType == null) { throw new BinderException("Couldn't figure out event type for method " + method + "."); } Method addListenerMethod = getAddListenerMethod(component.getClass(), eventType); if (addListenerMethod != null) { try { Object listener = createListenerProxy( addListenerMethod.getParameterTypes()[0], eventType, method, controller); addListenerMethod.invoke(component, listener); // TODO exception handling } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }
public void createDataset(Dataset dataset) { try { MongoProvider provider = new MongoProvider("localhost", 10000, "test", null, null); dsDao = new DatasetDao(); orgDao = new OrganizationDao(); org = new Organization(); org.setOrganizationId("orgId"); ArrayList<Dataset> datasets = new ArrayList<>(); datasets.add(dataset); org.setDatasets(datasets); org.setOrganizationUri("testUri"); org.setHarvestingMetadata(new HarvestingMetadata()); Field field; try { field = DatasetDao.class.getDeclaredField("provider"); field.setAccessible(true); field.set(dsDao, provider); field = OrganizationDao.class.getDeclaredField("provider"); field.setAccessible(true); field.set(orgDao, provider); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } dsDao.createDatasetForOrganization(org, dataset); orgDao.create(org); System.out.println( "Dataset: " + dsDao.getByName(dataset.getName()).getName() + " is saved in a virtual MongoDB"); try { List<Dataset> allDatasetsByOrganization = orgDao.getAllDatasetsByOrganization("orgId"); System.out.println("Datasets:"); for (Dataset ds : allDatasetsByOrganization) { System.out.println(ds.getName()); } } catch (NoOrganizationExceptionFound e) { e.printStackTrace(); } } catch (UnknownHostException e) { e.printStackTrace(); } }
/** * Try to execute given method on given object. Handles invocation target exceptions. XXX nearly * duplicates tryMethod in JGEngine. * * @return null means method does not exist or returned null/void */ static Object tryMethod(Object o, String name, Object[] args) { try { Method met = JREEngine.getMethod(o.getClass(), name, args); if (met == null) return null; return met.invoke(o, args); } catch (InvocationTargetException ex) { Throwable ex_t = ex.getTargetException(); ex_t.printStackTrace(); return null; } catch (IllegalAccessException ex) { System.err.println("Unexpected exception:"); ex.printStackTrace(); return null; } }
private void bindField( Component componentRoot, Object controller, Field field, UiField annotation) { String componentId = annotation.value(); Component component = Clara.findComponentById(componentRoot, componentId); if (component == null) { throw new BinderException("No component found for id: " + componentId + "."); } try { field.setAccessible(true); field.set(controller, component); // TODO exception handling } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } }
// Lookup the value corresponding to a key found in catalog.getKeys(). // Here we assume that the catalog returns a non-inherited value for // these keys. FIXME: Not true. Better see whether handleGetObject is // public - it is in ListResourceBundle and PropertyResourceBundle. private Object lookup(String key) { Object value = null; if (lookupMethod != null) { try { value = lookupMethod.invoke(catalog, new Object[] {key}); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.getTargetException().printStackTrace(); } } else { try { value = catalog.getObject(key); } catch (MissingResourceException e) { } } return value; }
public void propertyChange(PropertyChangeEvent e) { if (_squelchChangeEvents) return; PropertyEditor editor = (PropertyEditor) e.getSource(); PropertyDescriptor prop = (PropertyDescriptor) _editor2Prop.get(editor); Method writer = prop.getWriteMethod(); if (writer != null) { try { Object[] params = {editor.getValue()}; writer.invoke(_value, params); setObject(_value); firePropertyChange(_value, prop.getName(), null, editor.getValue()); } catch (IllegalAccessException ex) { ex.printStackTrace(); } catch (InvocationTargetException ex) { ex.getTargetException().printStackTrace(); } } }
public Matrix createVector() { int rows = frame.size(); Matrix m = new Matrix(rows, 1); for (int i = 0; i < rows; i++) { M rowValue = frame.object(i); try { Number numValue = (Number) numericField.get(rowValue); m.set(i, 0, numValue.doubleValue()); } catch (IllegalAccessException e) { e.printStackTrace(); throw new IllegalStateException( String.format("Couldn't access field %s: %s", numericField.getName(), e.getMessage())); } } return m; }
protected synchronized Message receiveMessage() throws IOException { if (messageBuffer.size() > 0) { Message m = (Message) messageBuffer.get(0); messageBuffer.remove(0); return m; } try { InetSocketAddress remoteAddress = (InetSocketAddress) channel.receive(receiveBuffer); if (remoteAddress != null) { int len = receiveBuffer.position(); receiveBuffer.rewind(); receiveBuffer.get(buf, 0, len); try { IP address = IP.fromInetAddress(remoteAddress.getAddress()); int port = remoteAddress.getPort(); extractor.appendData(buf, 0, len, new SocketDescriptor(address, port)); receiveBuffer.clear(); extractor.updateAvailableMessages(); return extractor.nextMessage(); } catch (EOFException exc) { exc.printStackTrace(); System.err.println(buf.length + ", " + len); } catch (InvocationTargetException exc) { exc.printStackTrace(); } catch (IllegalAccessException exc) { exc.printStackTrace(); } catch (InstantiationException exc) { exc.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvalidCompressionMethodException e) { e.printStackTrace(); } } } catch (ClosedChannelException exc) { if (isKeepAlive()) { throw exc; } } return null; }
/** * Fire an event to the registered listeners, but stop on a PropertyVetoException. Subclasses may * choose to implement their own fire method, and just use this class for the add/remove methods. * * @param evt the Event we're going to pass to the listeners * @throws java.beans.PropertyVetoException */ protected final void firePropertyEvent(Object evt, Method m) throws PropertyVetoException { // grab a reference to the listeners Object[] array = fListeners; if (array.length == 0) return; Object[] params = fCachedParams; if (params == null) params = new Object[] {evt}; // wasn't available, make a new array else { fCachedParams = null; // set to null in case fire is called re-entrantly params[0] = evt; } try { for (int i = 0; i < array.length; i++) { try { m.invoke(array[i], params); } catch (IllegalAccessException iae) { iae.printStackTrace(); } catch (InvocationTargetException ite) { Throwable t = ite.getTargetException(); if (t instanceof PropertyVetoException) throw ((PropertyVetoException) t); else t.printStackTrace(); } if ((evt instanceof Consumable) && ((Consumable) evt).isConsumed()) { if (gDebugEvents) Engine.debugLog("Consumed By : " + array[i]); return; } } } finally { // make our param array available for re-use // doesn't matter if we made it fresh, or already // reused it from a previous fire call params[0] = null; fCachedParams = params; } }
/** * オブジェクトのメソッドを呼び出す * * @param Object o メソッドを呼び出したいオブジェクト * @param String methodName 呼び出したいメソッドの名前 * @param Object... args メソッドのパラメータ * @throws NoSuchMethodException */ public static Object invoke(Object o, String methodName, Object... args) throws SecurityException, ClassNotFoundException, NoSuchMethodException { StringBuffer tempMessage = new StringBuffer(); Method method = null; // //argsArray:メソッドの引数の型配列 // Class<?>[] argsArray = new Class<?>[args.length]; // for(int i = 0; i < args.length; i++){ // argsArray[i] = getClassObject(args[i]); // //スーパークラスを引数にとれるように修正 // } // try { // method = o.getClass().getMethod(methodName, argsArray); // } catch (NoSuchMethodException e) { // try{ // method = o.getClass().getDeclaredMethod(methodName, argsArray); // }catch (NoSuchMethodException e2) { // message = "NoSuchMethodException\r\n"; // display.append(message); // } // } ///////////////////////////////////////// // argsArray:メソッドの引数の型配列 Class<?>[] argsArray = new Class<?>[args.length]; for (int i = 0; i < args.length; i++) { argsArray[i] = getClassObject(args[i]); } method = getMethod(o, args, methodName, argsArray); //////////////////////////////////////// tempMessage.append("method: " + method.getName() + " is called.\r\n"); if (Modifier.isPrivate(method.getModifiers())) { method.setAccessible(true); } if (o.equals(null)) { if (Modifier.isStatic(method.getModifiers()) == false) { throw new NoSuchMethodException(); } } try { Type returnType = method.getGenericReturnType(); tempMessage.append("return type: " + returnType.toString() + "\r\n"); if (returnType.equals(Void.TYPE)) { tempMessage.append("return value: " + "なし\r\n"); } else { tempMessage.append("return value: " + method.invoke(o, args).toString() + "\r\n"); } message = tempMessage.toString(); display.append(message); return method.invoke(o, args); } catch (IllegalArgumentException e) { e.printStackTrace(); message = tempMessage.append("IllegalArgumentException\r\n").toString(); display.append(message); } catch (IllegalAccessException e) { e.printStackTrace(); message = tempMessage.append("IllegalAccessException\r\n").toString(); display.append(message); } catch (InvocationTargetException e) { e.printStackTrace(); tempMessage.append("InvocationTargetException\r\n"); message = tempMessage.append(e.getCause().toString() + "\r\n").toString(); display.append(message); } return null; }
public static void main(String[] args) { // Obtain the class object if we know the name of the class Class rental = RentCar.class; try { // get the absolute name of the class String rentalClassPackage = rental.getName(); System.out.println("Class Name is: " + rentalClassPackage); // get the simple name of the class (without package info) String rentalClassNoPackage = rental.getSimpleName(); System.out.println("Class Name without package is: " + rentalClassNoPackage); // get the package name of the class Package rentalPackage = rental.getPackage(); System.out.println("Package Name is: " + rentalPackage); // get all the constructors of the class Constructor[] constructors = rental.getConstructors(); System.out.println("Constructors are: " + Arrays.toString(constructors)); // get constructor with specific argument Constructor constructor = rental.getConstructor(Integer.TYPE); // initializing an object of the RentCar class RentCar rent = (RentCar) constructor.newInstance(455); // get all methods of the class including declared methods of // superclasses // in that case, superclass of RentCar is the class java.lang.Object Method[] allmethods = rental.getMethods(); System.out.println("Methods are: " + Arrays.toString(allmethods)); for (Method method : allmethods) { System.out.println("method = " + method.getName()); } // get all methods declared in the class // but excludes inherited methods. Method[] declaredMethods = rental.getDeclaredMethods(); System.out.println("Declared Methods are: " + Arrays.toString(declaredMethods)); for (Method dmethod : declaredMethods) { System.out.println("method = " + dmethod.getName()); } // get method with specific name and parameters Method oneMethod = rental.getMethod("computeRentalCost", new Class[] {Integer.TYPE}); System.out.println("Method is: " + oneMethod); // call computeRentalCost method with parameter int oneMethod.invoke(rent, 4); // get all the parameters of computeRentalCost Class[] parameterTypes = oneMethod.getParameterTypes(); System.out.println( "Parameter types of computeRentalCost() are: " + Arrays.toString(parameterTypes)); // get the return type of computeRentalCost Class returnType = oneMethod.getReturnType(); System.out.println("Return type is: " + returnType); // gets all the public member fields of the class RentCar Field[] fields = rental.getFields(); System.out.println("Public Fields are: "); for (Field oneField : fields) { // get public field name Field field = rental.getField(oneField.getName()); String fieldname = field.getName(); System.out.println("Fieldname is: " + fieldname); // get public field type Object fieldType = field.getType(); System.out.println("Type of field " + fieldname + " is: " + fieldType); // get public field value Object value = field.get(rent); System.out.println("Value of field " + fieldname + " is: " + value); } // How to access private member fields of the class // getDeclaredField() returns the private field Field privateField = RentCar.class.getDeclaredField("type"); String name = privateField.getName(); System.out.println("One private Fieldname is: " + name); // makes this private field instance accessible // for reflection use only, not normal code privateField.setAccessible(true); // get the value of this private field String fieldValue = (String) privateField.get(rent); System.out.println("fieldValue = " + fieldValue); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } }
private void dump() throws IOException { lookupMethod = null; try { lookupMethod = catalog.getClass().getMethod("lookup", new Class[] {java.lang.String.class}); } catch (NoSuchMethodException e) { } catch (SecurityException e) { } Method pluralMethod = null; try { pluralMethod = catalog.getClass().getMethod("get_msgid_plural_table", new Class[0]); } catch (NoSuchMethodException e) { } catch (SecurityException e) { } Field pluralField = null; try { pluralField = catalog.getClass().getField("plural"); } catch (NoSuchFieldException e) { } catch (SecurityException e) { } // Search for the header entry. { Object header_entry = null; Enumeration keys = catalog.getKeys(); while (keys.hasMoreElements()) if ("".equals(keys.nextElement())) { header_entry = lookup(""); break; } // If there is no header entry, fake one. // FIXME: This is not needed; right after po_lex_charset_init set // the PO charset to UTF-8. if (header_entry == null) header_entry = "Content-Type: text/plain; charset=UTF-8\n"; dumpMessage("", null, header_entry); } // Now the other messages. { Enumeration keys = catalog.getKeys(); Object plural = null; if (pluralMethod != null) { // msgfmt versions > 0.13.1 create a static get_msgid_plural_table() // method. try { plural = pluralMethod.invoke(catalog, new Object[0]); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.getTargetException().printStackTrace(); } } else if (pluralField != null) { // msgfmt versions <= 0.13.1 create a static plural field. try { plural = pluralField.get(catalog); } catch (IllegalAccessException e) { e.printStackTrace(); } } if (plural instanceof String[]) { // A GNU gettext created class with plural handling, Java2 format. int i = 0; while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); Object value = lookup(key); String key_plural = (value instanceof String[] ? ((String[]) plural)[i++] : null); if (!"".equals(key)) dumpMessage(key, key_plural, value); } if (i != ((String[]) plural).length) throw new RuntimeException("wrong plural field length"); } else if (plural instanceof Hashtable) { // A GNU gettext created class with plural handling, Java format. while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); if (!"".equals(key)) { Object value = lookup(key); String key_plural = (value instanceof String[] ? (String) ((Hashtable) plural).get(key) : null); dumpMessage(key, key_plural, value); } } } else if (plural == null) { // No plural handling. while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); if (!"".equals(key)) dumpMessage(key, null, lookup(key)); } } else throw new RuntimeException("wrong plural field value"); } }