List of usage examples for java.lang.reflect Constructor setAccessible
@Override @CallerSensitive public void setAccessible(boolean flag)
A SecurityException is also thrown if this object is a Constructor object for the class Class and flag is true.
From source file:com.payu.sdk.util.UtilTest.java
/** * Private constructor test/* ww w . j a v a2 s .c om*/ * * @param clasz * @throws IllegalArgumentException * @throws InstantiationException * @throws IllegalAccessException * @throws InvocationTargetException */ @SuppressWarnings("rawtypes") private void privateConstructorTest(Class clasz) throws IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { Constructor[] ctors = clasz.getDeclaredConstructors(); Assert.assertEquals(1, ctors.length, "Utility class should only have one constructor"); Constructor ctor = ctors[0]; Assert.assertFalse(ctor.isAccessible(), "Utility class constructor should be inaccessible"); ctor.setAccessible(true); // obviously we'd never do this in production Assert.assertEquals(clasz, ctor.newInstance().getClass(), "You'd expect the construct to return the expected type"); }
From source file:com.codelanx.codelanxlib.command.CommandNode.java
/** * Creates a {@link PluginCommand} object with reflection, as the * constructor has protected access/* www .jav a 2s . com*/ * * @since 0.1.0 * @version 0.1.0 * * @param name The name of the command * @param plugin The {@link Plugin} relevant to the command * @return A new {@link PluginCommand} object, or {@code null} if the * creation of the object failed */ private PluginCommand getBukkitCommand(String name, Plugin plugin) { try { Constructor<PluginCommand> c = PluginCommand.class.getConstructor(String.class, Plugin.class); c.setAccessible(true); return c.newInstance(name, plugin); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException ex) { Debugger.error(ex, "Error aliasing bukkit command"); } return null; }
From source file:com.p5solutions.core.utils.ReflectionUtility.java
/** * New instance./*from ww w . j av a2s.c o m*/ * * @param <T> * the generic type * @param clazz * the clazz * @param paramTypes * the param types * @param arguments * the arguments * @return the t */ public static <T> T newInstance(Class<T> clazz, Class<?>[] paramTypes, Object[] arguments) { T instance = null; try { // Constructor<?>[] constructors = clazz.getDeclaredConstructors(); Constructor<T> constructor = clazz.getDeclaredConstructor(paramTypes); boolean access = constructor.isAccessible(); constructor.setAccessible(true); instance = constructor.newInstance(arguments); if (!access) { constructor.setAccessible(false); } } catch (Exception e) { logger.error(e); } return instance; }
From source file:org.j2free.servlet.EntityAdminServlet.java
/** * * @param request// www . j a v a 2 s . c o m * @param response * @throws ServletException * @throws IOException */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Controller controller = Controller.get(); // Get the controller associated with the current thread; String uri = request.getRequestURI(); uri = uri.replaceFirst(".*?/(list|find|inspect|create|save|update|delete)", "$1"); // chop off the part before what we care about String path[] = uri.split("/"); log.debug(uri); log.debug("path.length = " + path.length); if (path.length < 1) { log.debug("too little path info " + uri); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } RequestDispatcher rd = null; if (path[0].equals("list")) { log.debug("in list"); if (path.length < 2) { log.debug("too few parts for list"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } try { Class klass = entityLookup.get(path[1]); if (klass == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().println("Could not find class for entity type: " + path[1]); return; } Marshaller marshaller = ReflectionMarshaller.getForClass(klass); int start = ServletUtils.getIntParameter(request, "start", 0); int limit = ServletUtils.getIntParameter(request, "limit", 100); List entities; if (path.length == 3) { String[] stringIds = path[2].split(","); Object[] ignoredIds = new Object[stringIds.length]; Class idType = marshaller.getIdType(); // NOTE: this will only work with integer entityIds if (idType == Integer.class) { for (int i = 0; i < stringIds.length; i++) ignoredIds[i] = Integer.parseInt(stringIds[i]); } else if (idType == String.class) { for (int i = 0; i < stringIds.length; i++) ignoredIds[i] = stringIds[i]; } else if (idType == Long.class) { for (int i = 0; i < stringIds.length; i++) ignoredIds[i] = Long.parseLong(stringIds[i]); } entities = controller.listByCriterions(klass, start, limit, Order.asc(marshaller.getIdName()), Restrictions.not(Restrictions.in(marshaller.getIdName(), ignoredIds))); } else entities = controller.listByCriterions(klass, start, limit, Order.asc(marshaller.getIdName())); TreeMap<String, Object> entityMap = new TreeMap<String, Object>(); for (Object obj : entities) { entityMap.put(marshaller.extractId(obj).toString(), obj); } request.setAttribute("start", start); request.setAttribute("limit", limit); request.setAttribute("total", controller.count(klass)); request.setAttribute("simpleName", klass.getSimpleName()); request.setAttribute("package", klass.getPackage().getName() + "."); request.setAttribute("entities", entityMap); if (ServletUtils.getBooleanParameter(request, "selector", false)) rd = request.getRequestDispatcher(Dispatch.ENTITY_SELECTOR); else rd = request.getRequestDispatcher(Dispatch.ENTITY_LIST); } catch (Exception e) { log.error("Error listing entities", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } else if (path[0].equals("find") || path[0].equals("inspect")) { log.debug("in find"); if (path.length < 3) { log.debug("too few parts for find"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } try { Class klass = entityLookup.get(path[1]); if (klass == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().println("Could not find class for entity type: " + path[1]); return; } Marshaller marshaller = ReflectionMarshaller.getForClass(klass); Object entity = controller.findPrimaryKey(klass, marshaller.asIdType(path[2])); request.setAttribute("entity", entity); request.setAttribute("entityId", marshaller.extractId(entity)); request.setAttribute("fields", marshaller.marshallOut(entity, true)); if (path[0].equals("find")) rd = request.getRequestDispatcher(Dispatch.ENTITY_EDIT); else rd = request.getRequestDispatcher(Dispatch.ENTITY_INSPECT); } catch (Exception e) { log.error("error finding entity", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } else if (path[0].equals("create")) { log.debug("in create"); if (path.length < 2) { log.debug("too few parts for create"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } try { Class klass = entityLookup.get(path[1]); if (klass == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().println("Could not find class for entity type: " + path[1]); return; } Marshaller marshaller = ReflectionMarshaller.getForClass(klass); Constructor zeroArgsConst = klass.getConstructor(); if (!zeroArgsConst.isAccessible()) zeroArgsConst.setAccessible(true); Object entity = zeroArgsConst.newInstance(); request.setAttribute("simpleName", klass.getSimpleName()); request.setAttribute("package", klass.getPackage().getName() + "."); request.setAttribute("fields", marshaller.marshallOut(entity, true)); rd = request.getRequestDispatcher(Dispatch.ENTITY_CREATE); } catch (Exception e) { log.error("error creating entity", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } else if (path[0].equals("save")) { log.debug("in save"); if (path.length < 2) { log.debug("too few parts for save"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } Marshaller marshaller = null; try { Class klass = entityLookup.get(path[1]); if (klass == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().println("Could not find class for entity type: " + path[1]); return; } marshaller = ReflectionMarshaller.getForClass(klass); Object entity = klass.newInstance(); entity = marshaller.marshallIn(entity, request.getParameterMap(), controller); controller.persist(entity, true); if (controller.hasErrors()) { response.getWriter().println(controller.getErrorsAsString("<br />", true)); return; } else { response.setStatus(HttpServletResponse.SC_CREATED); // need this to display dates in the DB stored format entity = controller.findPrimaryKey(klass, marshaller.extractId(entity)); request.setAttribute("entity", entity); request.setAttribute("entityId", marshaller.extractId(entity)); request.setAttribute("fields", marshaller.marshallOut(entity, true)); rd = request.getRequestDispatcher(Dispatch.ENTITY_EDIT); } } catch (MarshallingException e) { log.error("error saving entity", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.getWriter().println(e.getMessage()); return; } catch (Exception e) { log.error("error saving entity", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } else if (path[0].equals("update")) { log.debug("in update"); if (path.length < 3) { log.debug("too few parts for update"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } try { Class klass = entityLookup.get(path[1]); if (klass == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().println("Could not find class for entity type: " + path[1]); return; } Marshaller marshaller = ReflectionMarshaller.getForClass(klass); Object entity = controller.findPrimaryKey(klass, marshaller.asIdType(path[2])); entity = marshaller.marshallIn(entity, request.getParameterMap(), controller); controller.merge(entity); if (controller.hasErrors()) { response.getWriter().println(controller.getErrorsAsString("<br />", true)); return; } else { response.setStatus(HttpServletResponse.SC_CREATED); // need this to display dates in the DB stored format entity = controller.findPrimaryKey(klass, marshaller.extractId(entity)); request.setAttribute("entity", entity); request.setAttribute("entityId", marshaller.extractId(entity)); request.setAttribute("fields", marshaller.marshallOut(entity, true)); rd = request.getRequestDispatcher(Dispatch.ENTITY_EDIT); } } catch (MarshallingException e) { log.error("error saving entity", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.getWriter().println(e.getMessage()); return; } catch (Exception e) { log.error("error updating entity", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } else if (path[0].equals("delete")) { log.debug("in delete"); if (path.length < 3) { log.debug("too few parts for delete"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } try { Class klass = entityLookup.get(path[1]); if (klass == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().println("Could not find class for entity type: " + path[1]); return; } Marshaller marshaller = ReflectionMarshaller.getForClass(klass); Object entity = controller.findPrimaryKey(klass, marshaller.asIdType(path[2])); controller.remove(entity); entity = null; controller.flush(); if (controller.hasErrors()) { response.getWriter().println(controller.getErrorsAsString("<br />", true)); return; } else { response.setStatus(HttpServletResponse.SC_CREATED); return; } } catch (Exception e) { log.error("error updating entity", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } else { log.debug("Don't know what to do!"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } CharArrayWrapper responseWrapper = new CharArrayWrapper((HttpServletResponse) response); rd.forward(request, responseWrapper); String responseString = responseWrapper.toString().replaceAll("\n", " ").replaceAll("\\s{2,}", " ") .replaceAll("> ", ">").replaceAll(" <", "<").replaceAll(" />", "/>"); response.setContentLength(responseString.length()); response.setContentType("text/javascript"); PrintWriter out = response.getWriter(); out.write(responseString); out.flush(); out.close(); }
From source file:io.realm.Realm.java
/** * Returns the default Realm module. This module contains all Realm classes in the current project, but not * those from library or project dependencies. Realm classes in these should be exposed using their own module. * * @return The default Realm module or null if no default module exists. * @see io.realm.RealmConfiguration.Builder#setModules(Object, Object...) *///w w w .j a v a 2s . c o m public static Object getDefaultModule() { String moduleName = "io.realm.DefaultRealmModule"; Class<?> clazz; try { clazz = Class.forName(moduleName); Constructor<?> constructor = clazz.getDeclaredConstructors()[0]; constructor.setAccessible(true); return constructor.newInstance(); } catch (ClassNotFoundException e) { return null; } catch (InvocationTargetException e) { throw new RealmException("Could not create an instance of " + moduleName, e); } catch (InstantiationException e) { throw new RealmException("Could not create an instance of " + moduleName, e); } catch (IllegalAccessException e) { throw new RealmException("Could not create an instance of " + moduleName, e); } }
From source file:org.apache.hadoop.hive.metastore.MetaStoreUtils.java
/** * Create an object of the given class.//from w w w. jav a2s . c om * @param theClass * @param parameterTypes * an array of parameterTypes for the constructor * @param initargs * the list of arguments for the constructor */ public static <T> T newInstance(Class<T> theClass, Class<?>[] parameterTypes, Object[] initargs) { // Perform some sanity checks on the arguments. if (parameterTypes.length != initargs.length) { throw new IllegalArgumentException( "Number of constructor parameter types doesn't match number of arguments"); } for (int i = 0; i < parameterTypes.length; i++) { Class<?> clazz = parameterTypes[i]; if (initargs[i] != null && !(clazz.isInstance(initargs[i]))) { throw new IllegalArgumentException("Object : " + initargs[i] + " is not an instance of " + clazz); } } try { Constructor<T> meth = theClass.getDeclaredConstructor(parameterTypes); meth.setAccessible(true); return meth.newInstance(initargs); } catch (Exception e) { throw new RuntimeException("Unable to instantiate " + theClass.getName(), e); } }
From source file:at.ac.tuwien.infosys.jcloudscale.classLoader.caching.fileCollectors.FileCollectorAbstract.java
/** * Collects the list of required files without content. * @param clazz the class that related files should be collected for. (joda style) * @return List of files that are required for specified class or * null if none are required. /*from w w w . j av a2 s .c o m*/ */ protected List<ClassLoaderFile> collectRequiredFiles(Class<?> clazz) { FileDependency fileDependency = clazz.getAnnotation(FileDependency.class); if (fileDependency == null) return null; List<ClassLoaderFile> files = new ArrayList<ClassLoaderFile>(); if (fileDependency.dependencyProvider().equals(IFileDependencyProvider.class)) {// we have static files // ContentType contentType = fileDependency.accessType() == FileAccess.ReadOnly ? // ContentType.ROFILE : ContentType.RWFILE; ContentType contentType = ContentType.ROFILE; String[] fileNames = fileDependency.files(); if (fileNames == null || fileNames.length == 0) return null; for (String filename : fileNames) { File file = RemoteClassLoaderUtils.getRelativePathFile(filename); if (!file.exists()) { log.severe("Class " + clazz.getName() + " set file " + filename + " as required, but the file is missing at " + file.getAbsolutePath()); continue; } files.add(new ClassLoaderFile(filename, file.lastModified(), file.length(), contentType)); } } else {// we have dynamic file list, let's process it. Class<? extends IFileDependencyProvider> dependentFilesProviderClass = fileDependency .dependencyProvider(); if (dependentFilesProviderClass == null) return null; //checking if we can create this class if (dependentFilesProviderClass.isInterface() || Modifier.isAbstract(dependentFilesProviderClass.getModifiers())) throw new JCloudScaleException("Class " + clazz.getName() + "is anotated with @FileDependency and has class " + dependentFilesProviderClass.getName() + " as dependency provider. However, dependency provider class is either abstract or interface."); if (dependentFilesProviderClass.getEnclosingClass() != null && !Modifier.isStatic(dependentFilesProviderClass.getModifiers())) throw new JCloudScaleException("Class " + clazz.getName() + "is anotated with @FileDependency and has class " + dependentFilesProviderClass.getName() + " as dependency provider. However, dependency provider class is internal and not static. The class has to be static in this case."); Constructor<? extends IFileDependencyProvider> constructor = null; try { constructor = dependentFilesProviderClass.getDeclaredConstructor(); } catch (NoSuchMethodException ex) { throw new JCloudScaleException(ex, "Class " + clazz.getName() + "is anotated with @FileDependency and has class " + dependentFilesProviderClass.getName() + " as dependency provider. However, dependency provider class cannot be created as it has no parameterless constructor."); } try { if (!constructor.isAccessible()) constructor.setAccessible(true); IFileDependencyProvider provider = constructor.newInstance(); for (DependentFile dependentFile : provider.getDependentFiles()) { File file = RemoteClassLoaderUtils.getRelativePathFile(dependentFile.filePath); if (!file.exists()) { log.severe("Class " + clazz.getName() + " set file " + dependentFile.filePath + " as required, but the file is missing."); continue; } // ContentType contentType = dependentFile.accessType == FileAccess.ReadOnly ? // ContentType.ROFILE : ContentType.RWFILE; ContentType contentType = ContentType.ROFILE; files.add(new ClassLoaderFile(file.getPath(), file.lastModified(), file.length(), contentType)); } } catch (Exception ex) { log.severe("Dependent files provider " + dependentFilesProviderClass.getName() + " for class " + clazz.getName() + " threw exception during execution:" + ex.toString()); throw new JCloudScaleException(ex, "Dependent files provider " + dependentFilesProviderClass.getName() + " for class " + clazz.getName() + " threw exception during execution."); } } return files; }
From source file:iristk.util.Record.java
@Override public Record clone() { try {// ww w . ja v a 2 s . c o m Constructor<?> constructor = getClass().getDeclaredConstructor(); constructor.setAccessible(true); Record clone = (Record) constructor.newInstance(null); clone.putAll(this); return clone; } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return null; }
From source file:iristk.util.Record.java
public Record deepClone() { try {//from ww w.j av a 2s. co m Constructor<?> constructor = getClass().getDeclaredConstructor(); constructor.setAccessible(true); Record clone = (Record) constructor.newInstance(null); for (String field : this.getFields()) { Object value = get(field); if (value != null) { if (value instanceof Record) clone.put(field, ((Record) value).deepClone()); else clone.put(field, value); } } return clone; } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } return null; }
From source file:com.helpinput.utils.Utils.java
public static <T> Constructor<?> findConstructor(Class<T> targetClass, Class<?>[] agrsClasses) { Constructor<?>[] constructors = targetClass.getDeclaredConstructors(); Constructor<?> theConstructor = null; for (Constructor<?> constructor : constructors) { Class<?>[] classes = constructor.getParameterTypes(); if (agrsClasses.length == 0 && classes.length == 0) { theConstructor = constructor; break; }//from ww w. ja va 2 s . co m if (agrsClasses.length == classes.length) { for (int i = 0; i < agrsClasses.length; i++) { if (agrsClasses[i] == null) { if (i == agrsClasses.length - 1) { theConstructor = constructor; break; } continue; } if (classes[i].isPrimitive()) { if (!primitiveWrap(classes[i]).isAssignableFrom(agrsClasses[i])) break; } else if (!classes[i].isAssignableFrom(agrsClasses[i])) break; if (i == agrsClasses.length - 1) { theConstructor = constructor; break; } } } if (theConstructor != null) break; } if (null != theConstructor) { if (!theConstructor.isAccessible()) theConstructor.setAccessible(true); return theConstructor; } else { if (targetClass.getSuperclass() != null) { return findConstructor(targetClass.getSuperclass(), agrsClasses); } return null; } }