/** * 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; }
/** 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 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(); } }
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(); } } }
/** * 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(); } }
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(); } } }
/** * 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); } }
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; }
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(); } }
/** 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数. */ public static void setFieldValue(final Object obj, final String fieldName, final Object value) { Field field = getAccessibleField(obj, fieldName); if (field == null) { throw new IllegalArgumentException( "Could not find field [" + fieldName + "] on target [" + obj + "]"); } try { field.set(obj, value); } catch (IllegalAccessException e) { logger.error("不可能抛出的异常:{}", e.getMessage()); } }
/** * Examines a property's type to see which method should be used to parse the property's value. * * @param desc The description of the property * @param element The XML element containing the property value * @return The value stored in the element * @throws IOException If there is an error reading the document */ public Object getObjectValue(PropertyDescriptor desc, Element element) throws IOException { // Find out what kind of property it is Class type = desc.getPropertyType(); // If it's an array, get the base type if (type.isArray()) { type = type.getComponentType(); } // For native types, object wrappers for natives, and strings, use the // basic parse routine if (type.equals(Integer.TYPE) || type.equals(Long.TYPE) || type.equals(Short.TYPE) || type.equals(Byte.TYPE) || type.equals(Boolean.TYPE) || type.equals(Float.TYPE) || type.equals(Double.TYPE) || Integer.class.isAssignableFrom(type) || Long.class.isAssignableFrom(type) || Short.class.isAssignableFrom(type) || Byte.class.isAssignableFrom(type) || Boolean.class.isAssignableFrom(type) || Float.class.isAssignableFrom(type) || Double.class.isAssignableFrom(type) || String.class.isAssignableFrom(type)) { return readBasicType(type, element); } else if (java.util.Date.class.isAssignableFrom(type)) { // If it's a date, use the date parser return readDate(element); } else { try { // If it's an object, create a new instance of the object (it should // be a bean, or there will be trouble) Object newOb = type.newInstance(); // Copy the XML element into the bean readObject(newOb, element); return newOb; } catch (InstantiationException exc) { throw new IOException( "Error creating object for " + desc.getName() + ": " + exc.toString()); } catch (IllegalAccessException exc) { throw new IOException( "Error creating object for " + desc.getName() + ": " + exc.toString()); } } }
/** * 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/protected修饰符, 不经过getter函数. */ public static Object getFieldValue(final Object obj, final String fieldName) { Field field = getAccessibleField(obj, fieldName); if (field == null) { throw new IllegalArgumentException( "Could not find field [" + fieldName + "] on target [" + obj + "]"); } Object result = null; try { result = field.get(obj); } catch (IllegalAccessException e) { logger.error("不可能抛出的异常{}", e.getMessage()); } return result; }
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; }
protected PsmEvent run(PsmEvent event, PsmInterp interp, Object[] argArray) { try { return (PsmEvent) method.invoke(null, argArray); } catch (IllegalAccessException ex) { // This really should never happen, given the checks at // construction time. throw new PsmMethodActionException(ex.toString()); } catch (InvocationTargetException ex) { // This may occur if the method throws a runtime exception. Rather // than wrap it in a PsmMethodActionException, let it percolate up. // If not a RuntimeException, wrap it in a PsmMethodActionException. Throwable th = ex.getTargetException(); if (th instanceof RuntimeException) { throw (RuntimeException) th; } else { throw new PsmMethodActionException( "Exception thrown from " + "target method invocation " + " is not a Runtime Exception", th); } } }
/** * Parses array from given JSONArray. Supports parsing of primitive types and {@link * com.vk.sdk.api.model.VKApiModel} instances. * * @param array JSONArray to parse * @param arrayClass type of array field in class. * @return object to set to array field in class * @throws org.json.JSONException if given array have incompatible type with given field. */ private static Object parseArrayViaReflection(JSONArray array, Class arrayClass) throws JSONException { Object result = Array.newInstance(arrayClass.getComponentType(), array.length()); Class<?> subType = arrayClass.getComponentType(); for (int i = 0; i < array.length(); i++) { try { Object item = array.opt(i); if (VKApiModel.class.isAssignableFrom(subType) && item instanceof JSONObject) { VKApiModel model = (VKApiModel) subType.newInstance(); item = model.parse((JSONObject) item); } Array.set(result, i, item); } catch (InstantiationException e) { throw new JSONException(e.getMessage()); } catch (IllegalAccessException e) { throw new JSONException(e.getMessage()); } catch (IllegalArgumentException e) { throw new JSONException(e.getMessage()); } } return result; }
/** * 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; }
/** * Parses object with follow rules: * * <p>1. All fields should had a public access. 2. The name of the filed should be fully equal to * name of JSONObject key. 3. Supports parse of all Java primitives, all {@link String}, arrays of * primitive types, {@link String}s and {@link com.vk.sdk.api.model.VKApiModel}s, list * implementation line {@link VKList}, {@link com.vk.sdk.api.model.VKAttachments.VKAttachment} or * {@link com.vk.sdk.api.model.VKPhotoSizes}, {@link com.vk.sdk.api.model.VKApiModel}s. * * <p>4. Boolean fields defines by vk_int == 1 expression. * * @param object object to initialize * @param source data to read values * @param <T> type of result * @return initialized according with given data object * @throws org.json.JSONException if source object structure is invalid */ @SuppressWarnings({"rawtypes", "unchecked"}) public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException { if (source.has("response")) { source = source.optJSONObject("response"); } if (source == null) { return object; } for (Field field : object.getClass().getFields()) { field.setAccessible(true); String fieldName = field.getName(); Class<?> fieldType = field.getType(); Object value = source.opt(fieldName); if (value == null) { continue; } try { if (fieldType.isPrimitive() && value instanceof Number) { Number number = (Number) value; if (fieldType.equals(int.class)) { field.setInt(object, number.intValue()); } else if (fieldType.equals(long.class)) { field.setLong(object, number.longValue()); } else if (fieldType.equals(float.class)) { field.setFloat(object, number.floatValue()); } else if (fieldType.equals(double.class)) { field.setDouble(object, number.doubleValue()); } else if (fieldType.equals(boolean.class)) { field.setBoolean(object, number.intValue() == 1); } else if (fieldType.equals(short.class)) { field.setShort(object, number.shortValue()); } else if (fieldType.equals(byte.class)) { field.setByte(object, number.byteValue()); } } else { Object result = field.get(object); if (value.getClass().equals(fieldType)) { result = value; } else if (fieldType.isArray() && value instanceof JSONArray) { result = parseArrayViaReflection((JSONArray) value, fieldType); } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) { Constructor<?> constructor = fieldType.getConstructor(JSONArray.class); result = constructor.newInstance((JSONArray) value); } else if (VKAttachments.class.isAssignableFrom(fieldType) && value instanceof JSONArray) { Constructor<?> constructor = fieldType.getConstructor(JSONArray.class); result = constructor.newInstance((JSONArray) value); } else if (VKList.class.equals(fieldType)) { ParameterizedType genericTypes = (ParameterizedType) field.getGenericType(); Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0]; if (VKApiModel.class.isAssignableFrom(genericType) && Parcelable.class.isAssignableFrom(genericType) && Identifiable.class.isAssignableFrom(genericType)) { if (value instanceof JSONArray) { result = new VKList((JSONArray) value, genericType); } else if (value instanceof JSONObject) { result = new VKList((JSONObject) value, genericType); } } } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) { result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value); } field.set(object, result); } } catch (InstantiationException e) { throw new JSONException(e.getMessage()); } catch (IllegalAccessException e) { throw new JSONException(e.getMessage()); } catch (NoSuchMethodException e) { throw new JSONException(e.getMessage()); } catch (InvocationTargetException e) { throw new JSONException(e.getMessage()); } catch (NoSuchMethodError e) { // Примечание Виталия: // Вы не поверите, но у некоторых вендоров getFields() вызывает ВОТ ЭТО. // Иногда я всерьез задумываюсь, правильно ли я поступил, выбрав Android в качестве // платформы разработки. throw new JSONException(e.getMessage()); } } return object; }
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"); } }
/** * Processes the request coming to the servlet and grabs the attributes set by the servlet and * uses them to fire off pre-determined methods set in the setupActionMethods function of the * servlet. * * @param request the http request coming from the browser. * @param response the http response going to the browser. * @throws javax.servlet.ServletException * @throws java.io.IOException */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!actionInitialized) { LogController.write(this, "This dispatcher servlet is not initialized properly!"); return; } if (actionTag == null) { LogController.write(this, "There is no action attribute tag name!"); return; } HttpSession httpSession = request.getSession(); UserSession userSession = (UserSession) httpSession.getAttribute("user_session"); if (userSession == null) { LogController.write(this, "User session is no longer available in this http session."); userSession = new UserSession(); // We always want a user session though... httpSession.setAttribute("user_session", userSession); } String action = (String) request.getAttribute(actionTag); try { if (action == null) { // There is no action attribute specified, check parameters. String external_action = (String) request.getParameter(actionTag); if (external_action != null) { Method method = externalActions.get(external_action); if (method != null) { LogController.write(this, "Performing external action: " + external_action); method.invoke(this, new Object[] {userSession, request, response}); } else { if (defaultExternalMethod != null) { LogController.write(this, "Performing default external action."); defaultExternalMethod.invoke(this, new Object[] {userSession, request, response}); } else { LogController.write(this, "Unable to perform default external action."); } } } else { if (defaultExternalMethod != null) { LogController.write(this, "Performing default external action."); defaultExternalMethod.invoke(this, new Object[] {userSession, request, response}); } else { LogController.write(this, "Unable to perform default external action."); } } } else { Method method = internalActions.get(action); if (method != null) { LogController.write(this, "Performing internal action: " + action); method.invoke(this, new Object[] {userSession, request, response}); } else { if (defaultInternalMethod != null) { LogController.write(this, "Performing default internal action."); defaultInternalMethod.invoke(this, new Object[] {userSession, request, response}); } else { LogController.write(this, "Unable to perform default internal action."); } } request.removeAttribute("application_action"); } } catch (IllegalAccessException accessEx) { LogController.write(this, "Exception while processing request: " + accessEx.getMessage()); } catch (InvocationTargetException invokeEx) { LogController.write(this, "Exception while processing request: " + invokeEx.toString()); invokeEx.printStackTrace(); } catch (Exception ex) { LogController.write(this, "Unknown exception: " + ex.toString()); } }
/** * Reads an XML element into a bean property by first locating the XML element corresponding to * this property. * * @param ob The bean whose property is being set * @param desc The property that will be set * @param nodes The list of XML items that may contain the property * @throws IOException If there is an error reading the document */ public void readProperty(Object ob, PropertyDescriptor desc, NodeList nodes, NamedNodeMap attrs) throws IOException { int numAttrs = attrs.getLength(); for (int i = 0; i < numAttrs; i++) { // See if the attribute name matches the property name if (namesMatch(desc.getName(), attrs.item(i).getNodeName())) { // Get the method used to set this property Method setter = desc.getWriteMethod(); // If this object has no setter, don't bother writing it if (setter == null) continue; // Get the value of the property Object obValue = getObjectValue(desc, attrs.item(i).getNodeValue()); if (obValue != null) { try { // Set the property value setter.invoke(ob, new Object[] {obValue}); } catch (InvocationTargetException exc) { throw new IOException( "Error setting property " + desc.getName() + ": " + exc.toString()); } catch (IllegalAccessException exc) { throw new IOException( "Error setting property " + desc.getName() + ": " + exc.toString()); } } return; } } int numNodes = nodes.getLength(); Vector arrayBuild = null; for (int i = 0; i < numNodes; i++) { Node node = nodes.item(i); // If this node isn't an element, skip it if (!(node instanceof Element)) continue; Element element = (Element) node; // See if the tag name matches the property name if (namesMatch(desc.getName(), element.getTagName())) { // Get the method used to set this property Method setter = desc.getWriteMethod(); // If this object has no setter, don't bother writing it if (setter == null) continue; // Get the value of the property Object obValue = getObjectValue(desc, element); // 070201 MAW: Modified from change submitted by Steve Poulson if (setter.getParameterTypes()[0].isArray()) { if (arrayBuild == null) { arrayBuild = new Vector(); } arrayBuild.addElement(obValue); // 070201 MAW: Go ahead and read through the rest of the nodes in case // another one matches the array. This has the effect of skipping // over the "return" statement down below continue; } if (obValue != null) { try { // Set the property value setter.invoke(ob, new Object[] {obValue}); } catch (InvocationTargetException exc) { throw new IOException( "Error setting property " + desc.getName() + ": " + exc.toString()); } catch (IllegalAccessException exc) { throw new IOException( "Error setting property " + desc.getName() + ": " + exc.toString()); } } return; } } // If we build a vector of array members, convert the vector into // an array and save it in the property if (arrayBuild != null) { // Get the method used to set this property Method setter = desc.getWriteMethod(); if (setter == null) return; Object[] obValues = (Object[]) Array.newInstance(desc.getPropertyType(), arrayBuild.size()); arrayBuild.copyInto(obValues); try { setter.invoke(ob, new Object[] {obValues}); } catch (InvocationTargetException exc) { throw new IOException("Error setting property " + desc.getName() + ": " + exc.toString()); } catch (IllegalAccessException exc) { throw new IOException("Error setting property " + desc.getName() + ": " + exc.toString()); } return; } }
/** * Reads XML element(s) into an indexed bean property by first locating the XML element(s) * corresponding to this property. * * @param ob The bean whose property is being set * @param desc The property that will be set * @param nodes The list of XML items that may contain the property * @throws IOException If there is an error reading the document */ public void readIndexedProperty( Object ob, IndexedPropertyDescriptor desc, NodeList nodes, NamedNodeMap attrs) throws IOException { // Create a vector to hold the property values Vector v = new Vector(); int numAttrs = attrs.getLength(); for (int i = 0; i < numAttrs; i++) { // See if this attribute matches the property name if (namesMatch(desc.getName(), attrs.item(i).getNodeName())) { // Get the property value Object obValue = getObjectValue(desc, attrs.item(i).getNodeValue()); if (obValue != null) { // Add the value to the list of values to be set v.addElement(obValue); } } } int numNodes = nodes.getLength(); for (int i = 0; i < numNodes; i++) { Node node = nodes.item(i); // Skip non-element nodes if (!(node instanceof Element)) continue; Element element = (Element) node; // See if this element tag matches the property name if (namesMatch(desc.getName(), element.getTagName())) { // Get the property value Object obValue = getObjectValue(desc, element); if (obValue != null) { // Add the value to the list of values to be set v.addElement(obValue); } } } // Get the method used to set the property value Method setter = desc.getWriteMethod(); // If this property has no setter, don't write it if (setter == null) return; // Create a new array of property values Object propArray = Array.newInstance(desc.getPropertyType().getComponentType(), v.size()); // Copy the vector into the array v.copyInto((Object[]) propArray); try { // Store the array of property values setter.invoke(ob, new Object[] {propArray}); } catch (InvocationTargetException exc) { throw new IOException("Error setting property " + desc.getName() + ": " + exc.toString()); } catch (IllegalAccessException exc) { throw new IOException("Error setting property " + desc.getName() + ": " + exc.toString()); } }
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(); } }