Java Code Examples for java.lang.reflect.Constructor#getDeclaringClass()

The following examples show how to use java.lang.reflect.Constructor#getDeclaringClass() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConstructorFromUnmarshaller.java    From jadira with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new instance
 * @param unmarshal Constructor to be used
 */
public ConstructorFromUnmarshaller(Constructor<S> unmarshal) {
    
    this.boundClass = unmarshal.getDeclaringClass();
    
    if (getBoundClass().isInterface() 
            || Modifier.isAbstract(getBoundClass().getModifiers()) 
            || getBoundClass().isLocalClass() 
            || getBoundClass().isMemberClass()) {
        throw new IllegalStateException("unmarshal constructor must have an instantiable target class");
    }
    
    if (unmarshal.getParameterTypes().length != 1) {
    	throw new IllegalStateException("unmarshal constructor must have a single parameter");
    }
    
    this.unmarshal = unmarshal;
    
    @SuppressWarnings("unchecked")
    Class<T> myTarget = (Class<T>)unmarshal.getParameterTypes()[0];
    this.targetClass = myTarget;
}
 
Example 2
Source File: ReflectionFactory.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
public final Constructor<?> newConstructorForSerialization(Class<?> cl,
                                                           Constructor<?> constructorToCall)
{
    if (constructorToCall.getDeclaringClass() == cl) {
        constructorToCall.setAccessible(true);
        return constructorToCall;
    }
    return generateConstructor(cl, constructorToCall);
}
 
Example 3
Source File: ConstructorResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected Constructor<?> getUserDeclaredConstructor(Constructor<?> constructor) {
	Class<?> declaringClass = constructor.getDeclaringClass();
	Class<?> userClass = ClassUtils.getUserClass(declaringClass);
	if (userClass != declaringClass) {
		try {
			return userClass.getDeclaredConstructor(constructor.getParameterTypes());
		}
		catch (NoSuchMethodException ex) {
			// No equivalent constructor on user class (superclass)...
			// Let's proceed with the given constructor as we usually would.
		}
	}
	return constructor;
}
 
Example 4
Source File: ReflectionFactory.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public ConstructorAccessor newConstructorAccessor(Constructor<?> c) {
    checkInitted();

    Class<?> declaringClass = c.getDeclaringClass();
    if (Modifier.isAbstract(declaringClass.getModifiers())) {
        return new InstantiationExceptionConstructorAccessorImpl(null);
    }
    if (declaringClass == Class.class) {
        return new InstantiationExceptionConstructorAccessorImpl
            ("Can not instantiate java.lang.Class");
    }
    // Bootstrapping issue: since we use Class.newInstance() in
    // the ConstructorAccessor generation process, we have to
    // break the cycle here.
    if (Reflection.isSubclassOf(declaringClass,
                                ConstructorAccessorImpl.class)) {
        return new BootstrapConstructorAccessorImpl(c);
    }

    if (noInflation && !ReflectUtil.isVMAnonymousClass(c.getDeclaringClass())) {
        return new MethodAccessorGenerator().
            generateConstructor(c.getDeclaringClass(),
                                c.getParameterTypes(),
                                c.getExceptionTypes(),
                                c.getModifiers());
    } else {
        NativeConstructorAccessorImpl acc =
            new NativeConstructorAccessorImpl(c);
        DelegatingConstructorAccessorImpl res =
            new DelegatingConstructorAccessorImpl(acc);
        acc.setParent(res);
        return res;
    }
}
 
Example 5
Source File: ReflectionFactory.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns an accessible constructor capable of creating instances
 * of the given class, initialized by the given constructor.
 *
 * @param classToInstantiate the class to instantiate
 * @param constructorToCall the constructor to call
 * @return an accessible constructor
 */
public Constructor<?> newConstructorForSerialization
    (Class<?> classToInstantiate, Constructor<?> constructorToCall)
{
    // Fast path
    if (constructorToCall.getDeclaringClass() == classToInstantiate) {
        return constructorToCall;
    }
    return generateConstructor(classToInstantiate, constructorToCall);
}
 
Example 6
Source File: LocalVariableTableParameterNameDiscoverer.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@Nullable
public String[] getParameterNames(Constructor<?> ctor) {
	Class<?> declaringClass = ctor.getDeclaringClass();
	Map<Member, String[]> map = this.parameterNamesCache.get(declaringClass);
	if (map == null) {
		map = inspectClass(declaringClass);
		this.parameterNamesCache.put(declaringClass, map);
	}
	if (map != NO_DEBUG_INFO_MAP) {
		return map.get(ctor);
	}
	return null;
}
 
Example 7
Source File: ObjectStreamClass.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Aggregate the ProtectionDomains of all the classes that separate
 * a concrete class {@code cl} from its ancestor's class declaring
 * a constructor {@code cons}.
 *
 * If {@code cl} is defined by the boot loader, or the constructor
 * {@code cons} is declared by {@code cl}, or if there is no security
 * manager, then this method does nothing and {@code null} is returned.
 *
 * @param cons A constructor declared by {@code cl} or one of its
 *             ancestors.
 * @param cl A concrete class, which is either the class declaring
 *           the constructor {@code cons}, or a serializable subclass
 *           of that class.
 * @return An array of ProtectionDomain representing the set of
 *         ProtectionDomain that separate the concrete class {@code cl}
 *         from its ancestor's declaring {@code cons}, or {@code null}.
 */
private ProtectionDomain[] getProtectionDomains(Constructor<?> cons,
                                                Class<?> cl) {
    ProtectionDomain[] domains = null;
    if (cons != null && cl.getClassLoader() != null
            && System.getSecurityManager() != null) {
        Class<?> cls = cl;
        Class<?> fnscl = cons.getDeclaringClass();
        Set<ProtectionDomain> pds = null;
        while (cls != fnscl) {
            ProtectionDomain pd = cls.getProtectionDomain();
            if (pd != null) {
                if (pds == null) pds = new HashSet<>();
                pds.add(pd);
            }
            cls = cls.getSuperclass();
            if (cls == null) {
                // that's not supposed to happen
                // make a ProtectionDomain with no permission.
                // should we throw instead?
                if (pds == null) pds = new HashSet<>();
                else pds.clear();
                pds.add(noPermissionsDomain());
                break;
            }
        }
        if (pds != null) {
            domains = pds.toArray(new ProtectionDomain[0]);
        }
    }
    return domains;
}
 
Example 8
Source File: ArchUnitException.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
public static ClassResolverConfigurationException onInstantiation(
        Constructor<?> constructor, List<String> args, Exception cause) {

    Class<?> declaringClass = constructor.getDeclaringClass();
    String message = String.format("class %s threw an exception in constructor %s('%s')",
            declaringClass.getName(), declaringClass.getSimpleName(), Joiner.on("', '").join(args));
    return new ClassResolverConfigurationException(message, cause);
}
 
Example 9
Source File: ObjectStreamClass.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Aggregate the ProtectionDomains of all the classes that separate
 * a concrete class {@code cl} from its ancestor's class declaring
 * a constructor {@code cons}.
 *
 * If {@code cl} is defined by the boot loader, or the constructor
 * {@code cons} is declared by {@code cl}, or if there is no security
 * manager, then this method does nothing and {@code null} is returned.
 *
 * @param cons A constructor declared by {@code cl} or one of its
 *             ancestors.
 * @param cl A concrete class, which is either the class declaring
 *           the constructor {@code cons}, or a serializable subclass
 *           of that class.
 * @return An array of ProtectionDomain representing the set of
 *         ProtectionDomain that separate the concrete class {@code cl}
 *         from its ancestor's declaring {@code cons}, or {@code null}.
 */
private ProtectionDomain[] getProtectionDomains(Constructor<?> cons,
                                                Class<?> cl) {
    ProtectionDomain[] domains = null;
    if (cons != null && cl.getClassLoader() != null
            && System.getSecurityManager() != null) {
        Class<?> cls = cl;
        Class<?> fnscl = cons.getDeclaringClass();
        Set<ProtectionDomain> pds = null;
        while (cls != fnscl) {
            ProtectionDomain pd = cls.getProtectionDomain();
            if (pd != null) {
                if (pds == null) pds = new HashSet<>();
                pds.add(pd);
            }
            cls = cls.getSuperclass();
            if (cls == null) {
                // that's not supposed to happen
                // make a ProtectionDomain with no permission.
                // should we throw instead?
                if (pds == null) pds = new HashSet<>();
                else pds.clear();
                pds.add(noPermissionsDomain());
                break;
            }
        }
        if (pds != null) {
            domains = pds.toArray(new ProtectionDomain[0]);
        }
    }
    return domains;
}
 
Example 10
Source File: UnsavedValueFactory.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static Object instantiate(Constructor constructor) {
	try {
		return constructor.newInstance(null);
	}
	catch (Exception e) {
		throw new InstantiationException( "could not instantiate test object", constructor.getDeclaringClass(), e );
	}
}
 
Example 11
Source File: ReflectUtils.java    From AndroidUtilCode with Apache License 2.0 5 votes vote down vote up
private ReflectUtils newInstance(final Constructor<?> constructor, final Object... args) {
    try {
        return new ReflectUtils(
                constructor.getDeclaringClass(),
                accessible(constructor).newInstance(args)
        );
    } catch (Exception e) {
        throw new ReflectException(e);
    }
}
 
Example 12
Source File: ActiveJpaAgentObjectFactory.java    From activejpa with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
public Object newInstance(Constructor constructor, Object... params) {
	Class<?> clazz = constructor.getDeclaringClass();
	try {
		clazz = loader.loadClass(clazz.getName());
		constructor = clazz.getConstructor(constructor.getParameterTypes());
		return constructor.newInstance(params);
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 13
Source File: ReflectionFactory.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public Constructor<?> newConstructorForSerialization
    (Class<?> classToInstantiate, Constructor<?> constructorToCall)
{
    // Fast path
    if (constructorToCall.getDeclaringClass() == classToInstantiate) {
        return constructorToCall;
    }

    ConstructorAccessor acc = new MethodAccessorGenerator().
        generateSerializationConstructor(classToInstantiate,
                                         constructorToCall.getParameterTypes(),
                                         constructorToCall.getExceptionTypes(),
                                         constructorToCall.getModifiers(),
                                         constructorToCall.getDeclaringClass());
    Constructor<?> c = newConstructor(constructorToCall.getDeclaringClass(),
                                      constructorToCall.getParameterTypes(),
                                      constructorToCall.getExceptionTypes(),
                                      constructorToCall.getModifiers(),
                                      langReflectAccess().
                                      getConstructorSlot(constructorToCall),
                                      langReflectAccess().
                                      getConstructorSignature(constructorToCall),
                                      langReflectAccess().
                                      getConstructorAnnotations(constructorToCall),
                                      langReflectAccess().
                                      getConstructorParameterAnnotations(constructorToCall));
    setConstructorAccessor(c, acc);
    return c;
}
 
Example 14
Source File: Expressions.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a NewExpression that represents calling the specified
 * constructor with the specified arguments.
 */
public static NewExpression new_(Constructor constructor,
    Iterable<? extends Expression> expressions) {
  // Note that the last argument is not an empty list. That would cause
  // an anonymous inner-class with no members to be generated.
  return new NewExpression(constructor.getDeclaringClass(),
      toList(expressions), null);
}
 
Example 15
Source File: Expressions.java    From Quicksql with MIT License 4 votes vote down vote up
/**
 * Creates a NewExpression that represents calling the specified
 * constructor with the specified arguments, using varargs.
 */
public static NewExpression new_(Constructor constructor,
    Expression... expressions) {
  return new NewExpression(constructor.getDeclaringClass(),
      toList(expressions), null);
}
 
Example 16
Source File: Expressions.java    From calcite with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a NewExpression that represents calling the specified
 * constructor with the specified arguments, using varargs.
 */
public static NewExpression new_(Constructor constructor,
    Expression... expressions) {
  return new NewExpression(constructor.getDeclaringClass(),
      toList(expressions), null);
}
 
Example 17
Source File: JavadocParanamer.java    From stategen with GNU Affero General Public License v3.0 4 votes vote down vote up
public String[] lookupParameterNames(AccessibleObject methodOrConstructor, boolean throwExceptionIfMissing) {
	if (methodOrConstructor == null)
		throw new NullPointerException();

	Class<?> klass;
	String name;
	Class<?>[] types;

	if (methodOrConstructor instanceof Constructor<?>) {
		Constructor<?> constructor = (Constructor<?>) methodOrConstructor;
		klass = constructor.getDeclaringClass();
		name = constructor.getName();
		types = constructor.getParameterTypes();
	} else if (methodOrConstructor instanceof Method) {
		Method method = (Method) methodOrConstructor;
		klass = method.getDeclaringClass();
		name = method.getName();
		types = method.getParameterTypes();
	} else
		throw new IllegalArgumentException();

	// quick check to see if we support the package
	if (!packages.contains(klass.getPackage().getName()))
		throw CLASS_NOT_SUPPORTED;

	try {
		String[] names = getParameterNames(klass, name, types);
		if (names == null) {
               if (throwExceptionIfMissing) {
                   throw new ParameterNamesNotFoundException(
				    methodOrConstructor.toString());
               } else {
                   return Paranamer.EMPTY_NAMES;
               }
           }
           return names;
	} catch (IOException e) {
           if (throwExceptionIfMissing) {
               throw new ParameterNamesNotFoundException(
    			methodOrConstructor.toString() + " due to an I/O error: "
	    				+ e.getMessage());
           } else {
               return Paranamer.EMPTY_NAMES;
           }
       }
}
 
Example 18
Source File: ConstructorCallStackManipulation.java    From jackson-modules-base with Apache License 2.0 4 votes vote down vote up
public KnownConstructorOfExistingType(Constructor<?> ctor,
                                      List<StackManipulation> constructorArgumentLoadingOperations) {
    super(constructorArgumentLoadingOperations);
    this.ctor = ctor;
    typeDescription = new TypeDescription.ForLoadedType(ctor.getDeclaringClass());
}
 
Example 19
Source File: UnsavedValueFactory.java    From lams with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Instantiate a class using the provided Constructor
 *
 * @param constructor The constructor
 *
 * @return The instantiated object
 *
 * @throws InstantiationException if something went wrong
 */
private static Object instantiate(Constructor constructor) {
	try {
		return constructor.newInstance();
	}
	catch (Exception e) {
		throw new InstantiationException( "could not instantiate test object", constructor.getDeclaringClass(), e );
	}
}
 
Example 20
Source File: Signature.java    From simplexml with Apache License 2.0 2 votes vote down vote up
/**
 * Constructor for the <code>Signature</code> object. This 
 * is used to create a hash map that can be used to acquire
 * parameters by name. It also provides the parameters in
 * declaration order within a for each loop.
 * 
 * @param factory this is the constructor this represents
 */
public Signature(Constructor factory) {
   this(factory, factory.getDeclaringClass());
}