List of usage examples for java.lang.reflect Constructor getModifiers
@Override public int getModifiers()
From source file:org.batoo.common.reflect.ReflectHelper.java
private static ConstructorAccessor createConstructorImpl(Constructor<?> constructor) { try {/*w w w. j a v a2s . c o m*/ final Class<?> magClass = Class.forName("sun.reflect.MethodAccessorGenerator"); final Constructor<?> c = magClass.getDeclaredConstructors()[0]; final Method generateMethod = magClass.getMethod("generateConstructor", Class.class, Class[].class, Class[].class, Integer.TYPE); ReflectHelper.setAccessible(c, true); ReflectHelper.setAccessible(generateMethod, true); try { final Object mag = c.newInstance(); return new SunConstructorAccessor( generateMethod.invoke(mag, constructor.getDeclaringClass(), constructor.getParameterTypes(), constructor.getExceptionTypes(), constructor.getModifiers())); } finally { ReflectHelper.setAccessible(c, false); ReflectHelper.setAccessible(generateMethod, false); } } catch (final Exception e) { throw new RuntimeException("Constructor generation failed", e); } }
From source file:org.apache.openjpa.enhance.PCSubclassValidator.java
public void assertCanSubclass() { Class superclass = meta.getDescribedType(); String name = superclass.getName(); if (superclass.isInterface()) addError(loc.get("subclasser-no-ifaces", name), meta); if (Modifier.isFinal(superclass.getModifiers())) addError(loc.get("subclasser-no-final-classes", name), meta); if (Modifier.isPrivate(superclass.getModifiers())) addError(loc.get("subclasser-no-private-classes", name), meta); if (PersistenceCapable.class.isAssignableFrom(superclass)) addError(loc.get("subclasser-super-already-pc", name), meta); try {/*from w w w . j a v a 2s .com*/ Constructor c = superclass.getDeclaredConstructor(new Class[0]); if (!(Modifier.isProtected(c.getModifiers()) || Modifier.isPublic(c.getModifiers()))) addError(loc.get("subclasser-private-ctor", name), meta); } catch (NoSuchMethodException e) { addError(loc.get("subclasser-no-void-ctor", name), meta); } // if the BCClass we loaded is already pc and the superclass is not, // then we should never get here, so let's make sure that the // calling context is caching correctly by throwing an exception. if (pc.isInstanceOf(PersistenceCapable.class) && !PersistenceCapable.class.isAssignableFrom(superclass)) throw new InternalException(loc.get("subclasser-class-already-pc", name)); if (AccessCode.isProperty(meta.getAccessType())) checkPropertiesAreInterceptable(); if (errors != null && !errors.isEmpty()) throw new UserException(errors.toString()); else if (contractViolations != null && !contractViolations.isEmpty() && log.isWarnEnabled()) log.warn(contractViolations.toString()); }
From source file:org.openo.nfvo.resmanagement.common.util.request.RequestUtilTest.java
@Test public void testPrivateConstructor() throws Exception { Constructor constructor = RequestUtil.class.getDeclaredConstructor(); assertTrue("Constructor is private", Modifier.isPrivate(constructor.getModifiers())); constructor.setAccessible(true);// ww w . j a v a2 s .c o m constructor.newInstance(); }
From source file:org.apromore.test.heuristic.JavaBeanHeuristic.java
private Object tryToInstantiate(Class clazz) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { Constructor constructor = clazz.getDeclaredConstructor(); // Default constructor must not be private. It can be protected or package-private though. if (!Modifier.isPrivate(constructor.getModifiers())) { constructor.setAccessible(true); }//from w w w .java2s. co m return constructor.newInstance(); }
From source file:com.stratio.es.utils.UtilESTest.java
@Test(expectedExceptions = InvocationTargetException.class) public void testConstructorIsPrivate() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Constructor<UtilES> constructor = UtilES.class.getDeclaredConstructor(); assertTrue(Modifier.isPrivate(constructor.getModifiers())); constructor.setAccessible(true);// w ww .ja va 2s .c o m constructor.newInstance(); }
From source file:com.flipkart.polyguice.dropwiz.PolyguiceApp.java
private Object createResource(Class<?> cls, T config, Environment env) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { LOGGER.debug("creating object of type {}", cls); try {/* w w w. j av a 2 s. c om*/ Constructor<?> ctor = cls.getConstructor(Configuration.class, Environment.class); int mod = ctor.getModifiers(); if (Modifier.isPublic(mod) && !Modifier.isAbstract(mod)) { LOGGER.debug("using ctor {}", ctor.toGenericString()); return ctor.newInstance(config, env); } } catch (NoSuchMethodException exep) { //NOOP, not even log } try { Constructor<?> ctor = cls.getConstructor(Environment.class, Configuration.class); int mod = ctor.getModifiers(); if (Modifier.isPublic(mod) && !Modifier.isAbstract(mod)) { LOGGER.debug("using ctor {}", ctor.toGenericString()); return ctor.newInstance(env, config); } } catch (NoSuchMethodException exep) { //NOOP, not even log } try { Constructor<?> ctor = cls.getConstructor(Configuration.class); int mod = ctor.getModifiers(); if (Modifier.isPublic(mod) && !Modifier.isAbstract(mod)) { LOGGER.debug("using ctor {}", ctor.toGenericString()); return ctor.newInstance(config); } } catch (NoSuchMethodException exep) { //NOOP, not even log } try { Constructor<?> ctor = cls.getConstructor(Environment.class); int mod = ctor.getModifiers(); if (Modifier.isPublic(mod) && !Modifier.isAbstract(mod)) { LOGGER.debug("using ctor {}", ctor.toGenericString()); return ctor.newInstance(env); } } catch (NoSuchMethodException exep) { //NOOP, not even log } try { Constructor<?> ctor = cls.getConstructor(); int mod = ctor.getModifiers(); if (Modifier.isPublic(mod) && !Modifier.isAbstract(mod)) { LOGGER.debug("using ctor {}", ctor.toGenericString()); return ctor.newInstance(); } } catch (NoSuchMethodException exep) { //NOOP, not even log } return null; }
From source file:RevEngAPI.java
/** Generate a .java file for the outline of the given class. */ public void doClass(Class c) throws IOException { className = c.getName();/* ww w . ja v a2 s. c o m*/ // pre-compute offset for stripping package name classNameOffset = className.lastIndexOf('.') + 1; // Inner class if (className.indexOf('$') != -1) return; // get name, as String, with . changed to / String slashName = className.replace('.', '/'); String fileName = slashName + ".java"; System.out.println(className + " --> " + fileName); String dirName = slashName.substring(0, slashName.lastIndexOf("/")); new File(dirName).mkdirs(); // create the file. PrintWriter out = new PrintWriter(new FileWriter(fileName)); out.println("// Generated by RevEngAPI for class " + className); // If in a package, say so. Package pkg; if ((pkg = c.getPackage()) != null) { out.println("package " + pkg.getName() + ';'); out.println(); } // print class header int cMods = c.getModifiers(); printMods(cMods, out); out.print("class "); out.print(trim(c.getName())); out.print(' '); // XXX get superclass out.println('{'); // print constructors Constructor[] ctors = c.getDeclaredConstructors(); for (int i = 0; i < ctors.length; i++) { if (i == 0) { out.println(); out.println("\t// Constructors"); } Constructor cons = ctors[i]; int mods = cons.getModifiers(); if (Modifier.isPrivate(mods)) continue; out.print('\t'); printMods(mods, out); out.print(trim(cons.getName()) + "("); Class[] classes = cons.getParameterTypes(); for (int j = 0; j < classes.length; j++) { if (j > 0) out.print(", "); out.print(trim(classes[j].getName()) + ' ' + mkName(PREFIX_ARG, j)); } out.println(") {"); out.print("\t}"); } // print method names Method[] mems = c.getDeclaredMethods(); for (int i = 0; i < mems.length; i++) { if (i == 0) { out.println(); out.println("\t// Methods"); } Method m = mems[i]; if (m.getName().startsWith("access$")) continue; int mods = m.getModifiers(); if (Modifier.isPrivate(mods)) continue; out.print('\t'); printMods(mods, out); out.print(m.getReturnType()); out.print(' '); out.print(trim(m.getName()) + "("); Class[] classes = m.getParameterTypes(); for (int j = 0; j < classes.length; j++) { if (j > 0) out.print(", "); out.print(trim(classes[j].getName()) + ' ' + mkName(PREFIX_ARG, j)); } out.println(") {"); out.println("\treturn " + defaultValue(m.getReturnType()) + ';'); out.println("\t}"); } // print fields Field[] flds = c.getDeclaredFields(); for (int i = 0; i < flds.length; i++) { if (i == 0) { out.println(); out.println("\t// Fields"); } Field f = flds[i]; int mods = f.getModifiers(); if (Modifier.isPrivate(mods)) continue; out.print('\t'); printMods(mods, out); out.print(trim(f.getType().getName())); out.print(' '); out.print(f.getName()); if (Modifier.isFinal(mods)) { try { out.print(" = " + f.get(null)); } catch (IllegalAccessException ex) { out.print("; // " + ex.toString()); } } out.println(';'); } out.println("}"); //out.flush(); out.close(); }
From source file:org.apache.poi.util.MethodUtils.java
public static <T> Constructor<T> getMatchingAccessibleConstructor(Class<T> clazz, Class[] parameterTypes) { // trace logging Log log = LogFactory.getLog(MethodUtils.class); MethodDescriptor md = new MethodDescriptor(clazz, "dummy", parameterTypes, false); // see if we can find the method directly // most of the time this works and it's much faster try {/*from w w w . j av a2 s .c o m*/ Constructor<T> constructor = clazz.getConstructor(parameterTypes); if (log.isTraceEnabled()) { log.trace("Found straight match: " + constructor); log.trace("isPublic:" + Modifier.isPublic(constructor.getModifiers())); } setMethodAccessible(constructor); // Default access superclass workaround return constructor; } catch (NoSuchMethodException e) { /* SWALLOW */ } // search through all methods int paramSize = parameterTypes.length; Constructor<T> bestMatch = null; Constructor<?>[] constructors = clazz.getConstructors(); float bestMatchCost = Float.MAX_VALUE; float myCost = Float.MAX_VALUE; for (int i = 0, size = constructors.length; i < size; i++) { // compare parameters Class[] methodsParams = constructors[i].getParameterTypes(); int methodParamSize = methodsParams.length; if (methodParamSize == paramSize) { boolean match = true; for (int n = 0; n < methodParamSize; n++) { if (log.isTraceEnabled()) { log.trace("Param=" + parameterTypes[n].getName()); log.trace("Method=" + methodsParams[n].getName()); } if (!isAssignmentCompatible(methodsParams[n], parameterTypes[n])) { if (log.isTraceEnabled()) { log.trace(methodsParams[n] + " is not assignable from " + parameterTypes[n]); } match = false; break; } } if (match) { // get accessible version of method Constructor<T> cons = (Constructor<T>) constructors[i]; myCost = getTotalTransformationCost(parameterTypes, cons.getParameterTypes()); if (myCost < bestMatchCost) { bestMatch = cons; bestMatchCost = myCost; } } } } if (bestMatch == null) { // didn't find a match log.trace("No match found."); } return bestMatch; }
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"); }//from ww w. ja va2s. c o m 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:com.basistech.rosette.apimodel.ModelTest.java
@Test public void packageTest() throws ClassNotFoundException, IllegalAccessException, InvocationTargetException, InstantiationException, IOException { Reflections reflections = new Reflections(this.getClass().getPackage().getName(), new SubTypesScanner(false)); Set<Class<?>> allClasses = reflections.getSubTypesOf(Object.class); for (Object clazz : allClasses) { String className = ((Class) clazz).getName(); if (className.contains("com.basistech.rosette.dm")) { continue; }//from w w w . ja v a 2s . c om if (className.contains("Adm")) { continue; // these are too hard. } if (className.endsWith(".ModelTest")) { continue; } if (className.endsWith(".NonNullTest")) { continue; } if (className.endsWith("Mixin")) { continue; } if (className.endsWith("Builder")) { continue; } if (className.contains(".batch.")) { // there are polymorphism issues in here for this test strategy. continue; } Class c = Class.forName(className); if (Modifier.isAbstract(c.getModifiers())) { continue; } Constructor[] ctors = c.getDeclaredConstructors(); if (ctors.length == 0) { continue; } Constructor ctor = ctors[0]; if (ctor.getParameterTypes().length == 0) { continue; // don't want empty constructor } Object o1; if (Modifier.isPublic(ctor.getModifiers())) { boolean oldInputStreams = inputStreams; try { if (className.endsWith("ConstantsResponse")) { inputStreams = false; // special case due to Object in there. } o1 = createObject(ctor); } finally { inputStreams = oldInputStreams; } // serialize // for a request, we might need a view ObjectWriter writer = mapper.writerWithView(Object.class); if (o1 instanceof DocumentRequest) { DocumentRequest r = (DocumentRequest) o1; if (r.getRawContent() instanceof String) { writer = mapper.writerWithView(DocumentRequestMixin.Views.Content.class); } } String json = writer.writeValueAsString(o1); // deserialize Object o2 = mapper.readValue(json, (Class<? extends Object>) clazz); // verify assertEquals(o1, o2); } } }