List of usage examples for java.lang Class getConstructor
@CallerSensitive public Constructor<T> getConstructor(Class<?>... parameterTypes) throws NoSuchMethodException, SecurityException
From source file:com.xhsoft.framework.common.utils.ClassUtil.java
/** * /*w w w . ja v a 2 s . com*/ * @param className * @param parent * @param parameters * @return * @throws ClassNotFoundException * @throws SecurityException * @throws NoSuchMethodException * @throws IllegalArgumentException * @throws InstantiationException * @throws IllegalAccessException * @throws InvocationTargetException - Object * @author: lizj */ public static Object getInstance(String className, String parent, Object[] parameters) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { Class<?> clazz = ClassUtil.getClass(className, parent); Class<?>[] types = null; if (parameters == null) { types = new Class[0]; } else { types = new Class[parameters.length]; } Constructor<?> c = clazz.getConstructor(types); return c.newInstance(parameters); }
From source file:com.vmware.identity.idm.server.ServerUtils.java
public static IDMException getRemoteException(Exception ex) { assert ((ex != null)); IDMException idmEx = null;/*from ww w. j a va 2 s . c om*/ logger.error(String.format("Exception '%s'", ex.toString()), ex); if (ex instanceof LoginException) { idmEx = new IDMLoginException(ex.getMessage()); } else if (ex instanceof ReferralLdapException) { return new IDMReferralException(ex.getMessage()); } else if (ex instanceof InvalidPrincipalException) { return new InvalidPrincipalException(ex.getMessage(), ((InvalidPrincipalException) ex).getPrincipal()); } else if (ex.getClass().equals(IDMLoginException.class)) { return new IDMLoginException(ex.getMessage(), ((IDMLoginException) ex).getUri()); } else if (ex instanceof IllegalArgumentException) { idmEx = new InvalidArgumentException(ex.getMessage()); } else if (ex instanceof IDMException) { idmEx = (IDMException) ex; // we do not expose the chain for any other exception // for IDM exception we should not do this also - // for one we don't want to expose it, for another chain could contain // exception types that RMI will not be able to create on the client // but if the chain is not present -> no need to do anything. if (idmEx.getCause() != null) { Class<? extends IDMException> theClass = idmEx.getClass(); try { idmEx = theClass.getConstructor(new Class[] { String.class }) .newInstance(new Object[] { idmEx.getMessage() }); } catch (Exception e) { // this should never fail, but to satisfy java checked exception error, we will fall back to // plain old IDM exception logger.error(String.format("Exception '%s'", ex.toString()), ex); idmEx = new IDMException(ex.getMessage()); } } } else { logger.error("Caught an unexpected exception", ex); idmEx = new IDMException(ex.getMessage()); } return idmEx; }
From source file:ch.flashcard.HibernateDetachUtility.java
private static void nullOutFieldsByFieldAccess(Object object, List<Field> classFields, Map<Integer, Object> checkedObjects, Map<Integer, List<Object>> checkedObjectCollisionMap, int depth, SerializationType serializationType) throws Exception { boolean accessModifierFlag = false; for (Field field : classFields) { accessModifierFlag = false;//from www. j a va2s.c o m if (!field.isAccessible()) { field.setAccessible(true); accessModifierFlag = true; } Object fieldValue = field.get(object); if (fieldValue instanceof HibernateProxy) { Object replacement = null; String assistClassName = fieldValue.getClass().getName(); if (assistClassName.contains("javassist") || assistClassName.contains("EnhancerByCGLIB")) { Class assistClass = fieldValue.getClass(); try { Method m = assistClass.getMethod("writeReplace"); replacement = m.invoke(fieldValue); String assistNameDelimiter = assistClassName.contains("javassist") ? "_$$_" : "$$"; assistClassName = assistClassName.substring(0, assistClassName.indexOf(assistNameDelimiter)); if (replacement != null && !replacement.getClass().getName().contains("hibernate")) { nullOutUninitializedFields(replacement, checkedObjects, checkedObjectCollisionMap, depth + 1, serializationType); field.set(object, replacement); } else { replacement = null; } } catch (Exception e) { LOG.error("Unable to write replace object " + fieldValue.getClass(), e); } } if (replacement == null) { String className = ((HibernateProxy) fieldValue).getHibernateLazyInitializer().getEntityName(); //see if there is a context classloader we should use instead of the current one. ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); Class clazz = contextClassLoader == null ? Class.forName(className) : Class.forName(className, true, contextClassLoader); Class[] constArgs = { Integer.class }; Constructor construct = null; try { construct = clazz.getConstructor(constArgs); replacement = construct.newInstance((Integer) ((HibernateProxy) fieldValue) .getHibernateLazyInitializer().getIdentifier()); field.set(object, replacement); } catch (NoSuchMethodException nsme) { try { Field idField = clazz.getDeclaredField("id"); Constructor ct = clazz.getDeclaredConstructor(); ct.setAccessible(true); replacement = ct.newInstance(); if (!idField.isAccessible()) { idField.setAccessible(true); } idField.set(replacement, (Integer) ((HibernateProxy) fieldValue) .getHibernateLazyInitializer().getIdentifier()); } catch (Exception e) { e.printStackTrace(); LOG.error("No id constructor and unable to set field id for base bean " + className, e); } field.set(object, replacement); } } } else { if (fieldValue instanceof PersistentCollection) { // Replace hibernate specific collection types if (!((PersistentCollection) fieldValue).wasInitialized()) { field.set(object, null); } else { Object replacement = null; boolean needToNullOutFields = true; // needed for BZ 688000 if (fieldValue instanceof Map) { replacement = new HashMap((Map) fieldValue); } else if (fieldValue instanceof List) { replacement = new ArrayList((List) fieldValue); } else if (fieldValue instanceof Set) { ArrayList l = new ArrayList((Set) fieldValue); // cannot recurse Sets, see BZ 688000 nullOutUninitializedFields(l, checkedObjects, checkedObjectCollisionMap, depth + 1, serializationType); replacement = new HashSet(l); // convert it back to a Set since that's the type of the real collection, see BZ 688000 needToNullOutFields = false; } else if (fieldValue instanceof Collection) { replacement = new ArrayList((Collection) fieldValue); } setField(object, field.getName(), replacement); if (needToNullOutFields) { nullOutUninitializedFields(replacement, checkedObjects, checkedObjectCollisionMap, depth + 1, serializationType); } } } else { if (fieldValue != null && (fieldValue.getClass().getName().contains("org.rhq") || fieldValue instanceof Collection || fieldValue instanceof Object[] || fieldValue instanceof Map)) nullOutUninitializedFields((fieldValue), checkedObjects, checkedObjectCollisionMap, depth + 1, serializationType); } } if (accessModifierFlag) { field.setAccessible(false); } } }
From source file:com.github.riking.dropcontrol.ItemStringInterpreter.java
public static BasicItemMatcher valueOf(String itemString) throws IllegalArgumentException { itemString = itemString.toUpperCase(); if (itemString.equals("ANY")) { return new BasicItemMatcher(null, null, null); }//w ww. j av a2 s. co m String[] split = itemString.split(":"); Validate.isTrue(split.length <= 2, "Unable to parse item string - too many colons (maximum 1). Please correct the format and reload the config. Input: " + itemString); Material mat = getMaterial(split[0]); Validate.notNull(mat, "Unable to parse item string - unrecognized material. Please correct the format and reload the config. Input: " + itemString); if (split.length == 1) { return new BasicItemMatcher(mat, null, null); } String dataString = split[1]; short data; try { data = Short.parseShort(dataString); return new BasicItemMatcher(mat, data, null); // the datastring is not passed if it was just a number } catch (NumberFormatException ignored) { } if (materialData.containsKey(mat.getData())) { Class<? extends MaterialData> matClass = mat.getData(); Class<? extends Enum> enumClass = materialData.get(mat.getData()); Enum enumValue; try { enumValue = (Enum) enumClass.getMethod("valueOf", String.class).invoke(null, dataString); } catch (InvocationTargetException e) { throw new IllegalArgumentException("Unable to parse item string - " + dataString + " is not a valid member of " + enumClass.getSimpleName(), e.getCause()); } catch (Exception rethrow) { throw new RuntimeException("Unexpected exception when parsing item string", rethrow); } MaterialData matData; try { matData = matClass.getConstructor(enumClass).newInstance(enumValue); } catch (Exception rethrow) { throw new RuntimeException("Unexpected exception when parsing item string", rethrow); } data = (short) matData.getData(); return new BasicItemMatcher(mat, data, dataString); } if (workarounds.containsKey(mat)) { StringInterpreter interp = workarounds.get(mat); data = interp.interpret(dataString); return new BasicItemMatcher(mat, data, dataString); } throw new IllegalArgumentException( "Unable to parse item string - I don't know how to parse a word-data for " + mat); }
From source file:com.nickandjerry.dynamiclayoutinflator.DynamicLayoutInflator.java
private static View getViewForName(Context context, String name) { try {/*from ww w.jav a 2 s.c om*/ if (!name.contains(".")) { name = "android.widget." + name; } Class<?> clazz = Class.forName(name); Constructor<?> constructor = clazz.getConstructor(Context.class); return (View) constructor.newInstance(context); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; }
From source file:com.roadmap.common.util.ObjectUtil.java
/** * Set the value of the specified property of the specified bean, * no matter which property reference format is used, with no type conversions. * * @param Object object whose property is to be modified * @param String possibly indexed and/or nested name of the property to be modified * @param Object value to which this property is to be set */// w ww.j av a2 s .c om @SuppressWarnings(value = { "unchecked", "rawtypes" }) public static void setPropertyValue(Object vo, String prop, Object value) { try { if (vo instanceof Map) { ((Map) vo).put(prop, value); } else { PropertyUtils.setProperty(vo, prop, value); } } catch (IllegalArgumentException iae) { try { Class cl = PropertyUtils.getPropertyType(vo, prop); String clName = cl.getName(); if (LONG.equalsIgnoreCase(clName)) { PropertyUtils.setProperty(vo, prop, Long.valueOf(RoadmapConstants.EMPTY_STRING + value)); } else if (INT.equalsIgnoreCase(clName) || INTEGER.equalsIgnoreCase(clName)) { PropertyUtils.setProperty(vo, prop, Integer.valueOf(RoadmapConstants.EMPTY_STRING + value)); } else if (BOOLEAN.equalsIgnoreCase(clName)) { PropertyUtils.setProperty(vo, prop, Boolean.valueOf(RoadmapConstants.EMPTY_STRING + value)); } else if (value != null && !value.getClass().getName().equals(clName)) { Constructor ctr = cl.getConstructor(value.getClass()); if (ctr != null) { PropertyUtils.setProperty(vo, prop, ctr.newInstance(value)); } } else { PropertyUtils.setProperty(vo, prop, value); } } catch (Exception e1) { // Supress errors // LoggingUtil.logError(logger, // "PayrollObjectUtility.setPropertyValue for object:" // + vo.getClass() + "|property:" + prop // + "|value:" + value, e1); } } catch (Exception e1) { // Supress errors // LoggingUtil.logError(logger, // "PayrollObjectUtility.setPropertyValue for object:" // + vo.getClass() + "|property:" + prop + "|value:" // + value, e1); } }
From source file:com.jims.oauth2.common.utils.OAuthUtils.java
public static <T> T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes, Object[] paramValues) throws OAuthSystemException { try {/*from w w w .java 2 s.c o m*/ if (paramsTypes != null && paramValues != null) { if (!(paramsTypes.length == paramValues.length)) { throw new IllegalArgumentException("Number of types and values must be equal"); } if (paramsTypes.length == 0 && paramValues.length == 0) { return clazz.newInstance(); } Constructor<T> clazzConstructor = clazz.getConstructor(paramsTypes); return clazzConstructor.newInstance(paramValues); } return clazz.newInstance(); } catch (NoSuchMethodException e) { throw new OAuthSystemException(e); } catch (InstantiationException e) { throw new OAuthSystemException(e); } catch (IllegalAccessException e) { throw new OAuthSystemException(e); } catch (InvocationTargetException e) { throw new OAuthSystemException(e); } }
From source file:com.jeeframework.util.classes.ClassUtils.java
/** * Determine whether the given class has a constructor with the given signature, * and return it if available (else return <code>null</code>). * <p>Essentially translates <code>NoSuchMethodException</code> to <code>null</code>. * @param clazz the clazz to analyze// w w w . j a va 2s . c o m * @param paramTypes the parameter types of the method * @return the constructor, or <code>null</code> if not found * @see java.lang.Class#getConstructor */ public static Constructor getConstructorIfAvailable(Class clazz, Class[] paramTypes) { Assert.notNull(clazz, "Class must not be null"); try { return clazz.getConstructor(paramTypes); } catch (NoSuchMethodException ex) { return null; } }
From source file:com.dngames.mobilewebcam.PhotoSettings.java
private static <T> T parseObjectFromString(String s, Class<T> c) throws Exception { return c.getConstructor(new Class[] { String.class }).newInstance(s); }
From source file:com.qubole.quark.plugins.jdbc.JdbcFactory.java
private DataSource getDataSource(Map<String, Object> properties, Class dbClass) throws QuarkException { try {/*from w w w . j av a 2s .c o m*/ return (DataSource) (dbClass.getConstructor(Map.class).newInstance(properties)); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException e) { throw new QuarkException(new Throwable("Invoking invalid constructor on class " + "specified for type " + properties.get("type") + ": " + dbClass.getCanonicalName())); } catch (InvocationTargetException e) { throw new QuarkException(e.getTargetException()); } }