List of usage examples for java.lang Class getConstructors
@CallerSensitive public Constructor<?>[] getConstructors() throws SecurityException
From source file:org.kepler.objectmanager.repository.RepositoryManager.java
/** * creates and instance of a repository// w w w . j a va 2 s . com * *@param newClass *@param arguments *@return Repository */ private Repository createInstance(Class newClass, Object[] arguments) throws Exception { Constructor[] constructors = newClass.getConstructors(); for (int i = 0; i < constructors.length; i++) { Constructor constructor = constructors[i]; Class[] parameterTypes = constructor.getParameterTypes(); for (int j = 0; j < parameterTypes.length; j++) { Class c = parameterTypes[j]; } if (parameterTypes.length != arguments.length) { continue; } boolean match = true; for (int j = 0; j < parameterTypes.length; j++) { if (!(parameterTypes[j].isInstance(arguments[j]))) { match = false; break; } } if (match) { Repository newRepository = (Repository) constructor.newInstance(arguments); return newRepository; } } // If we get here, then there is no matching constructor. // Generate a StringBuffer containing what we were looking for. StringBuffer argumentBuffer = new StringBuffer(); for (int i = 0; i < arguments.length; i++) { argumentBuffer.append(arguments[i].getClass() + " = \"" + arguments[i].toString() + "\""); if (i < (arguments.length - 1)) { argumentBuffer.append(", "); } } throw new Exception("Cannot find a suitable constructor (" + arguments.length + " args) (" + argumentBuffer + ") for '" + newClass.getName() + "'"); }
From source file:com.weibo.api.motan.core.extension.ExtensionLoader.java
private void checkConstructorPublic(Class<T> clz) { Constructor<?>[] constructors = clz.getConstructors(); if (constructors == null || constructors.length == 0) { failThrows(clz, "Error has no public no-args constructor"); }/* w w w. j a v a2 s . com*/ for (Constructor<?> constructor : constructors) { if (Modifier.isPublic(constructor.getModifiers()) && constructor.getParameterTypes().length == 0) { return; } } failThrows(clz, "Error has no public no-args constructor"); }
From source file:org.jolokia.converter.object.StringToObjectConverter.java
private Object convertByConstructor(String pType, String pValue) { Class<?> expectedClass = ClassUtil.classForName(pType); if (expectedClass != null) { for (Constructor<?> constructor : expectedClass.getConstructors()) { // only support only 1 constructor parameter if (constructor.getParameterTypes().length == 1 && constructor.getParameterTypes()[0].isAssignableFrom(String.class)) { try { return constructor.newInstance(pValue); } catch (Exception ignore) { }//from w ww .j a v a 2s .c o m } } } return null; }
From source file:de.mpg.mpi_inf.bioinf.netanalyzer.ui.ChartDisplayPanel.java
/** * Handles the pressing of the {@link #btnFilter} button. * <p>//from w w w . jav a 2 s .c o m * After asking the user for confirmation, this method adds or removes filter to the complex * parameter displayed. * </p> */ private void performFilter() { if (originalParam == visualizer.getComplexParam()) { // Create filter try { final Class<?> paramClass = originalParam.getClass(); final Class<?> filterClass = Plugin.getFilterDialogClass(paramClass); final Constructor<?> constr = filterClass.getConstructors()[0]; Object[] cParams = new Object[] { ownerDialog, Messages.DT_FILTERDATA, originalParam, visualizer.getSettings() }; ComplexParamFilterDialog d = (ComplexParamFilterDialog) constr.newInstance(cParams); ComplexParamFilter filter = d.showDialog(); if (filter != null) { btnFilter.setText(Messages.DI_REMOVEFILTER); btnFilter.setToolTipText(Messages.TT_REMOVEFILTER); visualizer.setComplexParam(filter.filter(originalParam)); chart = visualizer.createControl(); JFreeChartConn.setChart(chartPanel, chart); } } catch (InnerException ex) { // NetworkAnalyzer internal error logger.error(Messages.SM_LOGERROR, ex); } catch (SecurityException ex) { Utils.showErrorBox(this, Messages.DT_SECERROR, Messages.SM_SECERROR2); } catch (Exception ex) { // ClassCastException, ClassNotFoundException, IllegalAccessException // IllegalArgumentException, InstantiationException, InvocationTargetException // NetworkAnalyzer internal error logger.error(Messages.SM_LOGERROR, ex); } } else { // Remove filter int res = JOptionPane.showConfirmDialog(this, Messages.SM_REMOVEFILTER, Messages.DT_REMOVEFILTER, JOptionPane.YES_NO_OPTION); if (res == JOptionPane.YES_OPTION) { btnFilter.setText(Messages.DI_FILTERDATA); btnFilter.setToolTipText(Messages.TT_FILTERDATA); visualizer.setComplexParam(originalParam); chart = visualizer.createControl(); JFreeChartConn.setChart(chartPanel, chart); } } }
From source file:MyJavaP.java
/** * Format the fields and methods of one class, given its name. *//*from w w w .j a v a2 s .co m*/ protected void doClass(String className) { try { Class c = Class.forName(className); System.out.println(Modifier.toString(c.getModifiers()) + ' ' + c + " {"); int mods; Field fields[] = c.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { if (!Modifier.isPrivate(fields[i].getModifiers()) && !Modifier.isProtected(fields[i].getModifiers())) System.out.println("\t" + fields[i]); } Constructor[] constructors = c.getConstructors(); for (int j = 0; j < constructors.length; j++) { Constructor constructor = constructors[j]; System.out.println("\t" + constructor); } Method methods[] = c.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { if (!Modifier.isPrivate(methods[i].getModifiers()) && !Modifier.isProtected(methods[i].getModifiers())) System.out.println("\t" + methods[i]); } System.out.println("}"); } catch (ClassNotFoundException e) { System.err.println("Error: Class " + className + " not found!"); } catch (Exception e) { System.err.println(e); } }
From source file:br.com.nordestefomento.jrimum.utilix.Field.java
@SuppressWarnings("unchecked") private void readStringOrNumericField(String valueAsString) { Class<?> c = value.getClass(); for (Constructor<?> cons : c.getConstructors()) { if (cons.getParameterTypes().length == 1) { if (cons.getParameterTypes()[0].equals(String.class)) { try { value = (G) cons.newInstance(valueAsString); } catch (IllegalArgumentException e) { getGenericReadError(e, valueAsString).printStackTrace(); } catch (InstantiationException e) { getGenericReadError(e, valueAsString).printStackTrace(); } catch (IllegalAccessException e) { getGenericReadError(e, valueAsString).printStackTrace(); } catch (InvocationTargetException e) { getGenericReadError(e, valueAsString).printStackTrace(); }//from ww w . j a va 2 s .com } } } }
From source file:org.apache.empire.db.DBReader.java
/** * copied from org.apache.commons.beanutils.ConstructorUtils since it's private there *//*ww w. jav a 2s. c o m*/ @SuppressWarnings("unchecked") private static Constructor findMatchingAccessibleConstructor(Class clazz, Class[] parameterTypes) { // See if we can find the method directly // probably faster if it works // (I am not sure whether it's a good idea to run into Exceptions) // try { // Constructor ctor = clazz.getConstructor(parameterTypes); // try { // // see comment in org.apache.commons.beanutils.ConstructorUtils // ctor.setAccessible(true); // } catch (SecurityException se) { /* ignore */ } // return ctor; // } catch (NoSuchMethodException e) { /* SWALLOW */ } // search through all constructors int paramSize = parameterTypes.length; Constructor[] ctors = clazz.getConstructors(); for (int i = 0, size = ctors.length; i < size; i++) { // compare parameters Class[] ctorParams = ctors[i].getParameterTypes(); int ctorParamSize = ctorParams.length; if (ctorParamSize == paramSize) { // Param Size matches boolean match = true; for (int n = 0; n < ctorParamSize; n++) { if (!ObjectUtils.isAssignmentCompatible(ctorParams[n], parameterTypes[n])) { match = false; break; } } if (match) { // get accessible version of method Constructor ctor = ConstructorUtils.getAccessibleConstructor(ctors[i]); if (ctor != null) { try { ctor.setAccessible(true); } catch (SecurityException se) { /* ignore */ } return ctor; } } } } return null; }
From source file:org.springframework.web.method.annotation.ModelAttributeMethodProcessor.java
/** * Extension point to create the model attribute if not found in the model, * with subsequent parameter binding through bean properties (unless suppressed). * <p>The default implementation typically uses the unique public no-arg constructor * if available but also handles a "primary constructor" approach for data classes: * It understands the JavaBeans {@link ConstructorProperties} annotation as well as * runtime-retained parameter names in the bytecode, associating request parameters * with constructor arguments by name. If no such constructor is found, the default * constructor will be used (even if not public), assuming subsequent bean property * bindings through setter methods.//www. jav a2s .com * @param attributeName the name of the attribute (never {@code null}) * @param parameter the method parameter declaration * @param binderFactory for creating WebDataBinder instance * @param webRequest the current request * @return the created model attribute (never {@code null}) * @throws BindException in case of constructor argument binding failure * @throws Exception in case of constructor invocation failure * @see #constructAttribute(Constructor, String, WebDataBinderFactory, NativeWebRequest) * @see BeanUtils#findPrimaryConstructor(Class) */ protected Object createAttribute(String attributeName, MethodParameter parameter, WebDataBinderFactory binderFactory, NativeWebRequest webRequest) throws Exception { MethodParameter nestedParameter = parameter.nestedIfOptional(); Class<?> clazz = nestedParameter.getNestedParameterType(); Constructor<?> ctor = BeanUtils.findPrimaryConstructor(clazz); if (ctor == null) { Constructor<?>[] ctors = clazz.getConstructors(); if (ctors.length == 1) { ctor = ctors[0]; } else { try { ctor = clazz.getDeclaredConstructor(); } catch (NoSuchMethodException ex) { throw new IllegalStateException("No primary or default constructor found for " + clazz, ex); } } } Object attribute = constructAttribute(ctor, attributeName, binderFactory, webRequest); if (parameter != nestedParameter) { attribute = Optional.of(attribute); } return attribute; }
From source file:org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.java
/** * Create a custom DataAccessException, based on a given exception * class from a CustomSQLErrorCodesTranslation definition. * @param task readable text describing the task being attempted * @param sql SQL query or update that caused the problem. May be <code>null</code>. * @param sqlEx the offending SQLException * @param exceptionClass the exception class to use, as defined in the * CustomSQLErrorCodesTranslation definition * @return null if the custom exception could not be created, otherwise * the resulting DataAccessException. This exception should include the * sqlEx parameter as a nested root cause. * @see CustomSQLErrorCodesTranslation#setExceptionClass *///w w w . j a va 2s. co m protected DataAccessException createCustomException(String task, String sql, SQLException sqlEx, Class exceptionClass) { // find appropriate constructor try { int constructorType = 0; Constructor[] constructors = exceptionClass.getConstructors(); for (int i = 0; i < constructors.length; i++) { Class[] parameterTypes = constructors[i].getParameterTypes(); if (parameterTypes.length == 1 && parameterTypes[0].equals(String.class)) { if (constructorType < MESSAGE_ONLY_CONSTRUCTOR) constructorType = MESSAGE_ONLY_CONSTRUCTOR; } if (parameterTypes.length == 2 && parameterTypes[0].equals(String.class) && parameterTypes[1].equals(Throwable.class)) { if (constructorType < MESSAGE_THROWABLE_CONSTRUCTOR) constructorType = MESSAGE_THROWABLE_CONSTRUCTOR; } if (parameterTypes.length == 2 && parameterTypes[0].equals(String.class) && parameterTypes[1].equals(SQLException.class)) { if (constructorType < MESSAGE_SQLEX_CONSTRUCTOR) constructorType = MESSAGE_SQLEX_CONSTRUCTOR; } if (parameterTypes.length == 3 && parameterTypes[0].equals(String.class) && parameterTypes[1].equals(String.class) && parameterTypes[2].equals(Throwable.class)) { if (constructorType < MESSAGE_SQL_THROWABLE_CONSTRUCTOR) constructorType = MESSAGE_SQL_THROWABLE_CONSTRUCTOR; } if (parameterTypes.length == 3 && parameterTypes[0].equals(String.class) && parameterTypes[1].equals(String.class) && parameterTypes[2].equals(SQLException.class)) { if (constructorType < MESSAGE_SQL_SQLEX_CONSTRUCTOR) constructorType = MESSAGE_SQL_SQLEX_CONSTRUCTOR; } } // invoke constructor Constructor exceptionConstructor = null; switch (constructorType) { case MESSAGE_SQL_SQLEX_CONSTRUCTOR: Class[] messageAndSqlAndSqlExArgsClass = new Class[] { String.class, String.class, SQLException.class }; Object[] messageAndSqlAndSqlExArgs = new Object[] { task, sql, sqlEx }; exceptionConstructor = exceptionClass.getConstructor(messageAndSqlAndSqlExArgsClass); return (DataAccessException) exceptionConstructor.newInstance(messageAndSqlAndSqlExArgs); case MESSAGE_SQL_THROWABLE_CONSTRUCTOR: Class[] messageAndSqlAndThrowableArgsClass = new Class[] { String.class, String.class, Throwable.class }; Object[] messageAndSqlAndThrowableArgs = new Object[] { task, sql, sqlEx }; exceptionConstructor = exceptionClass.getConstructor(messageAndSqlAndThrowableArgsClass); return (DataAccessException) exceptionConstructor.newInstance(messageAndSqlAndThrowableArgs); case MESSAGE_SQLEX_CONSTRUCTOR: Class[] messageAndSqlExArgsClass = new Class[] { String.class, SQLException.class }; Object[] messageAndSqlExArgs = new Object[] { task + ": " + sqlEx.getMessage(), sqlEx }; exceptionConstructor = exceptionClass.getConstructor(messageAndSqlExArgsClass); return (DataAccessException) exceptionConstructor.newInstance(messageAndSqlExArgs); case MESSAGE_THROWABLE_CONSTRUCTOR: Class[] messageAndThrowableArgsClass = new Class[] { String.class, Throwable.class }; Object[] messageAndThrowableArgs = new Object[] { task + ": " + sqlEx.getMessage(), sqlEx }; exceptionConstructor = exceptionClass.getConstructor(messageAndThrowableArgsClass); return (DataAccessException) exceptionConstructor.newInstance(messageAndThrowableArgs); case MESSAGE_ONLY_CONSTRUCTOR: Class[] messageOnlyArgsClass = new Class[] { String.class }; Object[] messageOnlyArgs = new Object[] { task + ": " + sqlEx.getMessage() }; exceptionConstructor = exceptionClass.getConstructor(messageOnlyArgsClass); return (DataAccessException) exceptionConstructor.newInstance(messageOnlyArgs); default: logger.warn("Unable to find appropriate constructor of custom exception class [" + exceptionClass.getName() + "]"); return null; } } catch (Throwable ex) { if (logger.isWarnEnabled()) { logger.warn("Unable to instantiate custom exception class [" + exceptionClass.getName() + "]", ex); } return null; } }
From source file:org.akita.proxy.ProxyInvocationHandler.java
/** * Dynamic proxy invoke// w ww . ja va 2s.c o m */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { AkPOST akPost = method.getAnnotation(AkPOST.class); AkGET akGet = method.getAnnotation(AkGET.class); AkAPI akApi = method.getAnnotation(AkAPI.class); Annotation[][] annosArr = method.getParameterAnnotations(); String invokeUrl = akApi.url(); ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); // AkApiParams to hashmap, filter out of null-value HashMap<String, File> filesToSend = new HashMap<String, File>(); HashMap<String, String> paramsMapOri = new HashMap<String, String>(); HashMap<String, String> paramsMap = getRawApiParams2HashMap(annosArr, args, filesToSend, paramsMapOri); // Record this invocation ApiInvokeInfo apiInvokeInfo = new ApiInvokeInfo(); apiInvokeInfo.apiName = method.getName(); apiInvokeInfo.paramsMap.putAll(paramsMapOri); apiInvokeInfo.url = invokeUrl; // parse '{}'s in url invokeUrl = parseUrlbyParams(invokeUrl, paramsMap); // cleared hashmap to params, and filter out of the null value Iterator<Entry<String, String>> iter = paramsMap.entrySet().iterator(); while (iter.hasNext()) { Entry<String, String> entry = iter.next(); params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } // get the signature string if using AkSignature akSig = method.getAnnotation(AkSignature.class); if (akSig != null) { Class<?> clazzSignature = akSig.using(); if (clazzSignature.getInterfaces().length > 0 // TODO: NEED VERIFY WHEN I HAVE TIME && InvokeSignature.class.getName().equals(clazzSignature.getInterfaces()[0].getName())) { InvokeSignature is = (InvokeSignature) clazzSignature.getConstructors()[0].newInstance(); String sigValue = is.signature(akSig, invokeUrl, params, paramsMapOri); String sigParamName = is.getSignatureParamName(); if (sigValue != null && sigParamName != null && sigValue.length() > 0 && sigParamName.length() > 0) { params.add(new BasicNameValuePair(sigParamName, sigValue)); } } } // choose POST GET PUT DELETE to use for this invoke String retString = ""; if (akGet != null) { StringBuilder sbUrl = new StringBuilder(invokeUrl); if (!(invokeUrl.endsWith("?") || invokeUrl.endsWith("&"))) { sbUrl.append("?"); } for (NameValuePair nvp : params) { sbUrl.append(nvp.getName()); sbUrl.append("="); sbUrl.append(nvp.getValue()); sbUrl.append("&"); } // now default using UTF-8, maybe improved later retString = HttpInvoker.get(sbUrl.toString()); } else if (akPost != null) { if (filesToSend.isEmpty()) { retString = HttpInvoker.post(invokeUrl, params); } else { retString = HttpInvoker.postWithFilesUsingURLConnection(invokeUrl, params, filesToSend); } } else { // use POST for default retString = HttpInvoker.post(invokeUrl, params); } // invoked, then add to history //ApiStats.addApiInvocation(apiInvokeInfo); //Log.d(TAG, retString); // parse the return-string final Class<?> returnType = method.getReturnType(); try { if (String.class.equals(returnType)) { // the result return raw string return retString; } else { // return object using json decode return JsonMapper.json2pojo(retString, returnType); } } catch (Exception e) { Log.e(TAG, retString, e); // log can print the error return-string throw new AkInvokeException(AkInvokeException.CODE_JSONPROCESS_EXCEPTION, e.getMessage(), e); } }