List of usage examples for java.lang Class getDeclaringClass
@CallerSensitive public Class<?> getDeclaringClass() throws SecurityException
From source file:org.apache.click.util.ClickUtils.java
/** * Invoke the named method on the given target object and return the result. * * @param target the target object with the method to invoke * @param method the name of the method to invoke * @return Object the target method result */// ww w . j av a 2 s . com private static Object invokeMethod(Object target, String method) { if (target == null) { throw new IllegalArgumentException("Null target parameter"); } if (method == null) { throw new IllegalArgumentException("Null method parameter"); } Method targetMethod = null; boolean isAccessible = true; try { Class<?> targetClass = target.getClass(); targetMethod = targetClass.getMethod(method); // Change accessible for anonymous inner classes public methods // only. Conditional checks: // #1 - Target method is not accessible // #2 - Anonymous inner classes are not public // #3 - Only modify public methods // #4 - Anonymous inner classes have no declaring class // #5 - Anonymous inner classes have $ in name if (!targetMethod.isAccessible() && !Modifier.isPublic(targetClass.getModifiers()) && Modifier.isPublic(targetMethod.getModifiers()) && targetClass.getDeclaringClass() == null && targetClass.getName().indexOf('$') != -1) { isAccessible = false; targetMethod.setAccessible(true); } return targetMethod.invoke(target); } catch (InvocationTargetException ite) { Throwable e = ite.getTargetException(); if (e instanceof RuntimeException) { throw (RuntimeException) e; } else if (e instanceof Exception) { String msg = "Exception occurred invoking public method: " + targetMethod; throw new RuntimeException(msg, e); } else if (e instanceof Error) { String msg = "Error occurred invoking public method: " + targetMethod; throw new RuntimeException(msg, e); } else { String msg = "Error occurred invoking public method: " + targetMethod; throw new RuntimeException(msg, e); } } catch (Exception e) { String msg = "Exception occurred invoking public method: " + targetMethod; throw new RuntimeException(msg, e); } finally { if (targetMethod != null && !isAccessible) { targetMethod.setAccessible(false); } } }
From source file:org.apache.geode.internal.InternalDataSerializer.java
/** * Instantiates an instance of {@code DataSerializer} * * @throws IllegalArgumentException If the class can't be instantiated * * @see DataSerializer#register(Class)//from w w w . j a v a 2s.co m */ private static DataSerializer newInstance(Class c) { if (!DataSerializer.class.isAssignableFrom(c)) { throw new IllegalArgumentException(LocalizedStrings.DataSerializer_0_DOES_NOT_EXTEND_DATASERIALIZER .toLocalizedString(c.getName())); } Constructor init; try { init = c.getDeclaredConstructor(new Class[0]); } catch (NoSuchMethodException ignored) { StringId s = LocalizedStrings.DataSerializer_CLASS_0_DOES_NOT_HAVE_A_ZEROARGUMENT_CONSTRUCTOR; Object[] args = new Object[] { c.getName() }; if (c.getDeclaringClass() != null) { s = LocalizedStrings.DataSerializer_CLASS_0_DOES_NOT_HAVE_A_ZEROARGUMENT_CONSTRUCTOR_IT_IS_AN_INNER_CLASS_OF_1_SHOULD_IT_BE_A_STATIC_INNER_CLASS; args = new Object[] { c.getName(), c.getDeclaringClass() }; } throw new IllegalArgumentException(s.toLocalizedString(args)); } DataSerializer s; try { init.setAccessible(true); s = (DataSerializer) init.newInstance(new Object[0]); } catch (IllegalAccessException ignored) { throw new IllegalArgumentException( LocalizedStrings.DataSerializer_COULD_NOT_INSTANTIATE_AN_INSTANCE_OF_0 .toLocalizedString(c.getName())); } catch (InstantiationException ex) { throw new IllegalArgumentException( LocalizedStrings.DataSerializer_COULD_NOT_INSTANTIATE_AN_INSTANCE_OF_0 .toLocalizedString(c.getName()), ex); } catch (InvocationTargetException ex) { throw new IllegalArgumentException(LocalizedStrings.DataSerializer_WHILE_INSTANTIATING_AN_INSTANCE_OF_0 .toLocalizedString(c.getName()), ex); } return s; }
From source file:org.evosuite.testcase.TestCodeVisitor.java
/** * <p>/*from w w w .j av a2 s .com*/ * getClassName * </p> * * @param clazz * a {@link java.lang.Class} object. * @return a {@link java.lang.String} object. */ public String getClassName(Class<?> clazz) { if (classNames.containsKey(clazz)) return classNames.get(clazz); if (clazz.isArray()) { return getClassName(clazz.getComponentType()) + "[]"; } GenericClass c = new GenericClass(clazz); String name = c.getSimpleName(); if (classNames.values().contains(name)) { name = clazz.getCanonicalName(); } else { /* * If e.g. there is a foo.bar.IllegalStateException with * foo.bar being the SUT package, then we need to use the * full package name for java.lang.IllegalStateException */ String fullName = Properties.CLASS_PREFIX + "." + name; if (!fullName.equals(clazz.getCanonicalName())) { try { if (ResourceList.getInstance(TestGenerationContext.getInstance().getClassLoaderForSUT()) .hasClass(fullName)) { name = clazz.getCanonicalName(); } } catch (IllegalArgumentException e) { // If the classpath is not correct, then we just don't check // because that cannot happen in regular EvoSuite use, only // from test cases } } } // Ensure outer classes are imported as well Class<?> outerClass = clazz.getEnclosingClass(); if (outerClass != null) { String enclosingName = getClassName(outerClass); String simpleOuterName = outerClass.getSimpleName(); if (simpleOuterName.equals(enclosingName)) { name = enclosingName + name.substring(simpleOuterName.length()); } else { name = enclosingName + name.substring(name.lastIndexOf(simpleOuterName) + simpleOuterName.length()); } } Class<?> declaringClass = clazz.getDeclaringClass(); if (declaringClass != null) { getClassName(declaringClass); } // We can't use "Test" because of JUnit if (name.equals("Test")) { name = clazz.getCanonicalName(); } classNames.put(clazz, name); return name; }
From source file:org.datavec.api.transform.TransformProcess.java
private static ObjectMapper reinitializeMapperWithSubtypes(ObjectMapper mapper) { //Register concrete subtypes for JSON serialization List<Class<?>> classes = Arrays.<Class<?>>asList(Transform.class, Condition.class, Filter.class, IReducer.class); List<String> classNames = new ArrayList<>(6); for (Class<?> c : classes) classNames.add(c.getName());//from w ww .j av a2s .c o m // First: scan the classpath and find all instances of the 'baseClasses' classes if (subtypesClassCache == null) { List<Class<?>> interfaces = Arrays.<Class<?>>asList(Transform.class, Condition.class, Filter.class, IReducer.class); List<Class<?>> classesList = Arrays.<Class<?>>asList(); Collection<URL> urls = ClasspathHelper.forClassLoader(); List<URL> scanUrls = new ArrayList<>(); for (URL u : urls) { String path = u.getPath(); if (!path.matches(".*/jre/lib/.*jar")) { //Skip JRE/JDK JARs scanUrls.add(u); } } Reflections reflections = new Reflections( new ConfigurationBuilder().filterInputsBy(new FilterBuilder().exclude("^(?!.*\\.class$).*$") //Consider only .class files (to avoid debug messages etc. on .dlls, etc //Exclude the following: the assumption here is that no custom functionality will ever be present // under these package name prefixes. .exclude("^org.nd4j.*").exclude("^org.bytedeco.*") //JavaCPP .exclude("^com.fasterxml.*")//Jackson .exclude("^org.apache.*") //Apache commons, Spark, log4j etc .exclude("^org.projectlombok.*").exclude("^com.twelvemonkeys.*").exclude("^org.joda.*") .exclude("^org.slf4j.*").exclude("^com.google.*").exclude("^org.reflections.*") .exclude("^ch.qos.*") //Logback ).addUrls(scanUrls).setScanners(new DataVecSubTypesScanner(interfaces, classesList))); org.reflections.Store store = reflections.getStore(); Iterable<String> subtypesByName = store.getAll(DataVecSubTypesScanner.class.getSimpleName(), classNames); Set<? extends Class<?>> subtypeClasses = Sets.newHashSet(ReflectionUtils.forNames(subtypesByName)); subtypesClassCache = new HashSet<>(); for (Class<?> c : subtypeClasses) { if (Modifier.isAbstract(c.getModifiers()) || Modifier.isInterface(c.getModifiers())) { //log.info("Skipping abstract/interface: {}",c); continue; } subtypesClassCache.add(c); } } //Second: get all currently registered subtypes for this mapper Set<Class<?>> registeredSubtypes = new HashSet<>(); for (Class<?> c : classes) { AnnotatedClass ac = AnnotatedClass.construct(c, mapper.getSerializationConfig().getAnnotationIntrospector(), null); Collection<NamedType> types = mapper.getSubtypeResolver().collectAndResolveSubtypes(ac, mapper.getSerializationConfig(), mapper.getSerializationConfig().getAnnotationIntrospector()); for (NamedType nt : types) { registeredSubtypes.add(nt.getType()); } } //Third: register all _concrete_ subtypes that are not already registered List<NamedType> toRegister = new ArrayList<>(); for (Class<?> c : subtypesClassCache) { //Check if it's concrete or abstract... if (Modifier.isAbstract(c.getModifiers()) || Modifier.isInterface(c.getModifiers())) { //log.info("Skipping abstract/interface: {}",c); continue; } if (!registeredSubtypes.contains(c)) { String name; if (ClassUtils.isInnerClass(c)) { Class<?> c2 = c.getDeclaringClass(); name = c2.getSimpleName() + "$" + c.getSimpleName(); } else { name = c.getSimpleName(); } toRegister.add(new NamedType(c, name)); if (log.isDebugEnabled()) { for (Class<?> baseClass : classes) { if (baseClass.isAssignableFrom(c)) { log.debug("Registering class for JSON serialization: {} as subtype of {}", c.getName(), baseClass.getName()); break; } } } } } mapper.registerSubtypes(toRegister.toArray(new NamedType[toRegister.size()])); //Recreate the mapper (via copy), as mapper won't use registered subtypes after first use mapper = mapper.copy(); return mapper; }
From source file:org.deeplearning4j.nn.conf.NeuralNetConfiguration.java
private static synchronized void registerSubtypes(ObjectMapper mapper) { //Register concrete subtypes for JSON serialization List<Class<?>> classes = Arrays.<Class<?>>asList(InputPreProcessor.class, ILossFunction.class, IActivation.class, Layer.class, GraphVertex.class, ReconstructionDistribution.class); List<String> classNames = new ArrayList<>(6); for (Class<?> c : classes) classNames.add(c.getName());/*from w ww .j a v a 2s . c o m*/ // First: scan the classpath and find all instances of the 'baseClasses' classes if (subtypesClassCache == null) { //Check system property: String prop = System.getProperty(CUSTOM_FUNCTIONALITY); if (prop != null && !Boolean.parseBoolean(prop)) { subtypesClassCache = Collections.emptySet(); } else { List<Class<?>> interfaces = Arrays.<Class<?>>asList(InputPreProcessor.class, ILossFunction.class, IActivation.class, ReconstructionDistribution.class); List<Class<?>> classesList = Arrays.<Class<?>>asList(Layer.class, GraphVertex.class); Collection<URL> urls = ClasspathHelper.forClassLoader(); List<URL> scanUrls = new ArrayList<>(); for (URL u : urls) { String path = u.getPath(); if (!path.matches(".*/jre/lib/.*jar")) { //Skip JRE/JDK JARs scanUrls.add(u); } } Reflections reflections = new Reflections( new ConfigurationBuilder().filterInputsBy(new FilterBuilder().exclude("^(?!.*\\.class$).*$") //Consider only .class files (to avoid debug messages etc. on .dlls, etc //Exclude the following: the assumption here is that no custom functionality will ever be present // under these package name prefixes. These are all common dependencies for DL4J .exclude("^org.nd4j.*").exclude("^org.datavec.*").exclude("^org.bytedeco.*") //JavaCPP .exclude("^com.fasterxml.*")//Jackson .exclude("^org.apache.*") //Apache commons, Spark, log4j etc .exclude("^org.projectlombok.*").exclude("^com.twelvemonkeys.*") .exclude("^org.joda.*").exclude("^org.slf4j.*").exclude("^com.google.*") .exclude("^org.reflections.*").exclude("^ch.qos.*") //Logback ).addUrls(scanUrls).setScanners(new DL4JSubTypesScanner(interfaces, classesList))); org.reflections.Store store = reflections.getStore(); Iterable<String> subtypesByName = store.getAll(DL4JSubTypesScanner.class.getSimpleName(), classNames); Set<? extends Class<?>> subtypeClasses = Sets.newHashSet(ReflectionUtils.forNames(subtypesByName)); subtypesClassCache = new HashSet<>(); for (Class<?> c : subtypeClasses) { if (Modifier.isAbstract(c.getModifiers()) || Modifier.isInterface(c.getModifiers())) { //log.info("Skipping abstract/interface: {}",c); continue; } subtypesClassCache.add(c); } } } //Second: get all currently registered subtypes for this mapper Set<Class<?>> registeredSubtypes = new HashSet<>(); for (Class<?> c : classes) { AnnotatedClass ac = AnnotatedClass.construct(c, mapper.getSerializationConfig().getAnnotationIntrospector(), null); Collection<NamedType> types = mapper.getSubtypeResolver().collectAndResolveSubtypes(ac, mapper.getSerializationConfig(), mapper.getSerializationConfig().getAnnotationIntrospector()); for (NamedType nt : types) { registeredSubtypes.add(nt.getType()); } } //Third: register all _concrete_ subtypes that are not already registered List<NamedType> toRegister = new ArrayList<>(); for (Class<?> c : subtypesClassCache) { //Check if it's concrete or abstract... if (Modifier.isAbstract(c.getModifiers()) || Modifier.isInterface(c.getModifiers())) { //log.info("Skipping abstract/interface: {}",c); continue; } if (!registeredSubtypes.contains(c)) { String name; if (ClassUtils.isInnerClass(c)) { Class<?> c2 = c.getDeclaringClass(); name = c2.getSimpleName() + "$" + c.getSimpleName(); } else { name = c.getSimpleName(); } toRegister.add(new NamedType(c, name)); if (log.isDebugEnabled()) { for (Class<?> baseClass : classes) { if (baseClass.isAssignableFrom(c)) { log.debug("Registering class for JSON serialization: {} as subtype of {}", c.getName(), baseClass.getName()); break; } } } } } mapper.registerSubtypes(toRegister.toArray(new NamedType[toRegister.size()])); }
From source file:org.regenstrief.util.Util.java
/** * Returns the full class name for the given Class * /* w w w .j a va 2 s . co m*/ * @param c the Class for which to find the name * @return the full class name **/ public static final String getFullClassName(final Class<?> c) { if (c.isArray()) { return getFullClassName(c.getComponentType()) + "[]"; } final Class<?> declaringClass = c.getDeclaringClass(); if (declaringClass != null) { return getFullClassName(declaringClass) + '.' + lookupClassName(c); } return lookupClassName(c); }