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

The following examples show how to use java.lang.reflect.Constructor#setAccessible() . 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: RegistryServer.java    From Jupiter with Apache License 2.0 6 votes vote down vote up
private static RegistryServer newInstance(Object... parameters) {
    if (defaultRegistryClass == null || allConstructorsParameterTypes == null) {
        throw new UnsupportedOperationException("Unsupported default registry");
    }

    // 根据JLS方法调用的静态分派规则查找最匹配的方法parameterTypes
    Class<?>[] parameterTypes = Reflects.findMatchingParameterTypes(allConstructorsParameterTypes, parameters);
    if (parameterTypes == null) {
        throw new IllegalArgumentException("Parameter types");
    }

    try {
        Constructor<RegistryServer> c = defaultRegistryClass.getConstructor(parameterTypes);
        c.setAccessible(true);
        return c.newInstance(parameters);
    } catch (Exception e) {
        ThrowUtil.throwException(e);
    }
    return null; // should never get here
}
 
Example 2
Source File: ObjectStreamClass.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns subclass-accessible no-arg constructor of first non-serializable
 * superclass, or null if none found.  Access checks are disabled on the
 * returned constructor (if any).
 */
private static Constructor getSerializableConstructor(Class<?> cl) {
    Class<?> initCl = cl;
    while (Serializable.class.isAssignableFrom(initCl)) {
        if ((initCl = initCl.getSuperclass()) == null) {
            return null;
        }
    }
    try {
        Constructor cons = initCl.getDeclaredConstructor(new Class<?>[0]);
        int mods = cons.getModifiers();
        if ((mods & Modifier.PRIVATE) != 0 ||
            ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) == 0 &&
             !packageEquals(cl, initCl)))
        {
            return null;
        }
        cons = bridge.newConstructorForSerialization(cl, cons);
        cons.setAccessible(true);
        return cons;
    } catch (NoSuchMethodException ex) {
        return null;
    }
}
 
Example 3
Source File: ClientDynamic.java    From pampas with Apache License 2.0 6 votes vote down vote up
public static <ReqT, RespT> void autoCall() throws Exception {
        DynamicMultiClassLoader loader = DynamicMultiClassLoader.getLoader(toUrl("/home/darrenfu/IdeaProjects/pampas/pampas-grpc/df/open/grpc/hello/grpc-test-229014610914606914.jar"));
        Class grpc = loader.load("df.open.grpc.hello.HelloServiceGrpc");
        Class proto = loader.load("df.open.grpc.hello.HelloServiceProto");
        Method getSayHelloMethod = grpc.getDeclaredMethod("getSayHelloMethod");
        MethodDescriptor<ReqT, RespT> methodDescriptor = (MethodDescriptor) getSayHelloMethod.invoke(grpc);

        ClientCall<ReqT, RespT> call =
                new ForwardingClientCall.SimpleForwardingClientCall(channel.newCall(methodDescriptor, callOption.withDeadlineAfter(timeout, TimeUnit.MILLISECONDS))) {

                    public void start(Listener responseListener, Metadata headers) {
                        System.out.println("start call......");
                        super.start(responseListener, headers);
                    }
                };
//        ClientCalls.asyncUnaryCall(call, (ReqT) req.newInstance(), responseFuture);
        Class<?> reqClz = Class.forName("df.open.grpc.hello.HelloServiceProto$HelloReq", false, loader);
        Constructor<?> constructor = reqClz.getDeclaredConstructor();
        constructor.setAccessible(true);
        System.out.println(constructor.isAccessible());

        RespT respT = ClientCalls.blockingUnaryCall(call, (ReqT) constructor.newInstance());
        System.out.println(respT);
        System.out.println("XXXXXXXxx");

    }
 
Example 4
Source File: SkinAppCompatViewInflater.java    From ReadMark with Apache License 2.0 6 votes vote down vote up
private View createView(Context context, String name, String prefix)
        throws ClassNotFoundException, InflateException {
    Constructor<? extends View> constructor = sConstructorMap.get(name);

    try {
        if (constructor == null) {
            // Class not found in the cache, see if it's real, and try to add it
            Class<? extends View> clazz = context.getClassLoader().loadClass(
                    prefix != null ? (prefix + name) : name).asSubclass(View.class);

            constructor = clazz.getConstructor(sConstructorSignature);
            sConstructorMap.put(name, constructor);
        }
        constructor.setAccessible(true);
        return constructor.newInstance(mConstructorArgs);
    } catch (Exception e) {
        // We do not want to catch these, lets return null and let the actual LayoutInflater
        // try
        return null;
    }
}
 
Example 5
Source File: ReflectionUtils.java    From incubator-ratis with Apache License 2.0 6 votes vote down vote up
private static <T> Constructor<T> get(Class<T> clazz, Class<?>[] argClasses)
    throws NoSuchMethodException {
  Objects.requireNonNull(clazz, "clazz == null");

  final List<Class<?>> key = new ArrayList<>(argClasses.length + 1);
  key.add(clazz);
  key.addAll(Arrays.asList(argClasses));

  @SuppressWarnings("unchecked")
  Constructor<T> ctor = (Constructor<T>) CONSTRUCTORS.get(key);
  if (ctor == null) {
    ctor = clazz.getDeclaredConstructor(argClasses);
    ctor.setAccessible(true);
    CONSTRUCTORS.put(key, ctor);
  }
  return ctor;
}
 
Example 6
Source File: ReflectUtils.java    From xdroid with Apache License 2.0 5 votes vote down vote up
public static <T> T newInstance(Class<T> clazz, Class<?>[] parameterTypes, Object[] args) {
    try {
        Constructor<T> ctor = clazz.getDeclaredConstructor(parameterTypes);
        ctor.setAccessible(true);
        return ctor.newInstance(args);
    } catch (Throwable ex) {
        throw new IllegalStateException(ex);
    }
}
 
Example 7
Source File: PreferenceCompatFragment.java    From Audinaut with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Access methods with visibility private
 **/

private PreferenceManager createPreferenceManager() {
    try {
        Constructor<PreferenceManager> c = PreferenceManager.class.getDeclaredConstructor(Activity.class, int.class);
        c.setAccessible(true);
        return c.newInstance(this.getActivity(), FIRST_REQUEST_CODE);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 8
Source File: Parser.java    From RDFS with Apache License 2.0 5 votes vote down vote up
/**
 * For a given identifier, add a mapping to the nodetype for the parse
 * tree and to the ComposableRecordReader to be created, including the
 * formals required to invoke the constructor.
 * The nodetype and constructor signature should be filled in from the
 * child node.
 */
protected static void addIdentifier(String ident, Class<?>[] mcstrSig,
                          Class<? extends Node> nodetype,
                          Class<? extends ComposableRecordReader> cl)
    throws NoSuchMethodException {
  Constructor<? extends Node> ncstr =
    nodetype.getDeclaredConstructor(ncstrSig);
  ncstr.setAccessible(true);
  nodeCstrMap.put(ident, ncstr);
  Constructor<? extends ComposableRecordReader> mcstr =
    cl.getDeclaredConstructor(mcstrSig);
  mcstr.setAccessible(true);
  rrCstrMap.put(ident, mcstr);
}
 
Example 9
Source File: ObjectStreamClass.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns public no-arg constructor of given class, or null if none found.
 * Access checks are disabled on the returned constructor (if any), since
 * the defining class may still be non-public.
 */
private static Constructor getExternalizableConstructor(Class<?> cl) {
    try {
        Constructor cons = cl.getDeclaredConstructor(new Class<?>[0]);
        cons.setAccessible(true);
        return ((cons.getModifiers() & Modifier.PUBLIC) != 0) ?
            cons : null;
    } catch (NoSuchMethodException ex) {
        return null;
    }
}
 
Example 10
Source File: ServcesManager.java    From letv with Apache License 2.0 5 votes vote down vote up
private void handleCreateServiceOne(Context hostContext, Intent stubIntent, ServiceInfo info) throws Exception {
    ResolveInfo resolveInfo = hostContext.getPackageManager().resolveService(stubIntent, 0);
    ServiceInfo stubInfo = resolveInfo != null ? resolveInfo.serviceInfo : null;
    ApkManager.getInstance().reportMyProcessName(stubInfo.processName, info.processName, info.packageName);
    PluginProcessManager.preLoadApk(hostContext, info);
    Object activityThread = ActivityThreadCompat.currentActivityThread();
    Object fakeToken = new MyFakeIBinder();
    Constructor init = Class.forName(ActivityThreadCompat.activityThreadClass().getName() + "$CreateServiceData").getDeclaredConstructor(new Class[0]);
    if (!init.isAccessible()) {
        init.setAccessible(true);
    }
    Object data = init.newInstance(new Object[0]);
    FieldUtils.writeField(data, UserInfoDb.TOKEN, fakeToken);
    FieldUtils.writeField(data, "info", (Object) info);
    if (VERSION.SDK_INT >= 11) {
        FieldUtils.writeField(data, "compatInfo", CompatibilityInfoCompat.DEFAULT_COMPATIBILITY_INFO());
    }
    Method method = activityThread.getClass().getDeclaredMethod("handleCreateService", new Class[]{CreateServiceData});
    if (!method.isAccessible()) {
        method.setAccessible(true);
    }
    method.invoke(activityThread, new Object[]{data});
    Object mService = FieldUtils.readField(activityThread, "mServices");
    Service service = (Service) MethodUtils.invokeMethod(mService, "get", fakeToken);
    MethodUtils.invokeMethod(mService, "remove", fakeToken);
    this.mTokenServices.put(fakeToken, service);
    this.mNameService.put(info.name, service);
    if (stubInfo != null) {
        ApkManager.getInstance().onServiceCreated(stubInfo, info);
    }
}
 
Example 11
Source File: SimpleHttpUpgradeHandshake.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public Constructor<String> run() throws Exception {
    Constructor<String> c;
    c = String.class.getDeclaredConstructor(char[].class, boolean.class);
    c.setAccessible(true);
    return c;
}
 
Example 12
Source File: Hex.java    From titan1withtp3.1 with Apache License 2.0 5 votes vote down vote up
/**
 * Used to get access to protected/private constructor of the specified class
 *
 * @param klass      - name of the class
 * @param paramTypes - types of the constructor parameters
 * @return Constructor if successful, null if the constructor cannot be
 *         accessed
 */
public static Constructor getProtectedConstructor(Class klass, Class... paramTypes) {
    Constructor c;
    try {
        c = klass.getDeclaredConstructor(paramTypes);
        c.setAccessible(true);
        return c;
    } catch (Exception e) {
        return null;
    }
}
 
Example 13
Source File: VMMonitor.java    From vi with Apache License 2.0 5 votes vote down vote up
public synchronized boolean init() {
    try {

        Class<?> vmIdentifierClass = Tools.loadJDKToolClass(VM_IDENTIFIER_CLASS_NAME);
        Class<?> monitoredHostClass = Tools.loadJDKToolClass(MONITORED_HOST_CLASS_NAME);
        Class<?> monitordVmClass = Tools.loadJDKToolClass(MONITORED_VM_CLASS_NAME);
        Class<?> monitorClass = Tools.loadJDKToolClass(MONITOR_CLASS_NAME);


        Constructor constructor = vmIdentifierClass.getDeclaredConstructor(String.class);
        constructor.setAccessible(true);
        Object vmIdentifier = constructor.newInstance(Tools.currentPID());
        MethodHandle getMonitoredHostMH = MethodHandles.lookup().findStatic(monitoredHostClass, "getMonitoredHost",
                MethodType.methodType(monitoredHostClass, vmIdentifierClass) );
        Object monitoredHost = getMonitoredHostMH.invoke(vmIdentifier);

        MethodHandle getMonitoredVMMH = MethodHandles.lookup().findVirtual(monitoredHostClass,"getMonitoredVm",
                MethodType.methodType(monitordVmClass, vmIdentifierClass));

        detachMH = MethodHandles.lookup().findVirtual(monitordVmClass,"detach",MethodType.methodType(void.class));
        findByNameMH = MethodHandles.lookup().findVirtual(monitordVmClass,"findByName",
                MethodType.methodType(monitorClass,String.class));
        getValueMH = MethodHandles.lookup().findVirtual(monitorClass,"getValue",MethodType.methodType(Object.class));
        VM = getMonitoredVMMH.invoke(monitoredHost,vmIdentifier);


    }catch (Throwable e){
        logger.warn("attach failed!",e);
        return false;
    }
    return true;
}
 
Example 14
Source File: Reflection.java    From SkyblockAddons with MIT License 5 votes vote down vote up
/**
 * Gets a constructor with the matching parameter types.
 * <p>
 * The parameter types are automatically checked against assignable types and primitives.
 * <p>
 * Super classes are automatically checked.
 *
 * @param paramTypes The types of parameters to look for.
 * @return The constructor with matching parameter types.
 * @throws ReflectionException When the class or constructor cannot be located.
 */
public final ConstructorAccessor getConstructor(Class<?>... paramTypes) throws ReflectionException {
	Class<?>[] types = toPrimitiveTypeArray(paramTypes);

	if (CONSTRUCTOR_CACHE.containsKey(this.getClazzPath())) {
		Map<Class<?>[], ConstructorAccessor> constructors = CONSTRUCTOR_CACHE.get(this.getClazzPath());

		for (Map.Entry<Class<?>[], ConstructorAccessor> entry : constructors.entrySet()) {
			if (Arrays.equals(entry.getKey(), types)) {
				return entry.getValue();
			}
		}
	} else
		CONSTRUCTOR_CACHE.put(this.getClazzPath(), new HashMap<>());

	for (Constructor<?> constructor : this.getClazz().getDeclaredConstructors()) {
		Class<?>[] constructorTypes = toPrimitiveTypeArray(constructor.getParameterTypes());

		if (isEqualsTypeArray(constructorTypes, types)) {
			constructor.setAccessible(true);
			ConstructorAccessor constructorAccessor = new ConstructorAccessor(this, constructor);
			CONSTRUCTOR_CACHE.get(this.getClazzPath()).put(types, constructorAccessor);
			return constructorAccessor;
		}
	}

	if (this.getClazz().getSuperclass() != null)
		return this.getSuperReflection().getConstructor(paramTypes);

	throw new ReflectionException(StringUtil.format("The constructor {0} was not found!", Arrays.asList(types)));
}
 
Example 15
Source File: JDKUtil.java    From marshalsec with MIT License 5 votes vote down vote up
@SuppressWarnings ( "resource" )
public static Object makeIteratorTriggerNative ( UtilFactory uf, Object it ) throws Exception, ClassNotFoundException, NoSuchMethodException,
        InstantiationException, IllegalAccessException, InvocationTargetException {
    Cipher m = Reflections.createWithoutConstructor(NullCipher.class);
    Reflections.setFieldValue(m, "serviceIterator", it);
    Reflections.setFieldValue(m, "lock", new Object());

    InputStream cos = new CipherInputStream(null, m);

    Class<?> niCl = Class.forName("java.lang.ProcessBuilder$NullInputStream"); //$NON-NLS-1$
    Constructor<?> niCons = niCl.getDeclaredConstructor();
    niCons.setAccessible(true);

    Reflections.setFieldValue(cos, "input", niCons.newInstance());
    Reflections.setFieldValue(cos, "ibuffer", new byte[0]);

    Object b64Data = Class.forName("com.sun.xml.internal.bind.v2.runtime.unmarshaller.Base64Data").newInstance();
    DataSource ds = (DataSource) Reflections
            .createWithoutConstructor(Class.forName("com.sun.xml.internal.ws.encoding.xml.XMLMessage$XmlDataSource")); //$NON-NLS-1$
    Reflections.setFieldValue(ds, "is", cos);
    Reflections.setFieldValue(b64Data, "dataHandler", new DataHandler(ds));
    Reflections.setFieldValue(b64Data, "data", null);

    Object nativeString = Reflections.createWithoutConstructor(Class.forName("jdk.nashorn.internal.objects.NativeString"));
    Reflections.setFieldValue(nativeString, "value", b64Data);
    return uf.makeHashCodeTrigger(nativeString);
}
 
Example 16
Source File: CommonUtil.java    From ChangeSkin with MIT License 5 votes vote down vote up
public static Logger createLoggerFromJDK(java.util.logging.Logger parent) {
    try {
        parent.setLevel(Level.ALL);

        Class<JDK14LoggerAdapter> adapterClass = JDK14LoggerAdapter.class;
        Constructor<JDK14LoggerAdapter> cons = adapterClass.getDeclaredConstructor(java.util.logging.Logger.class);
        cons.setAccessible(true);
        return cons.newInstance(parent);
    } catch (ReflectiveOperationException reflectEx) {
        parent.log(Level.WARNING, "Cannot create slf4j logging adapter", reflectEx);
        parent.log(Level.WARNING, "Creating logger instance manually...");
        return LoggerFactory.getLogger(parent.getName());
    }
}
 
Example 17
Source File: NBTIntegerList.java    From Item-NBT-API with MIT License 5 votes vote down vote up
@Override
protected Object asTag(Integer object) {
	try {
		Constructor<?> con = ClassWrapper.NMS_NBTTAGINT.getClazz().getDeclaredConstructor(int.class);
		con.setAccessible(true);
		return con.newInstance(object);
	} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
			| NoSuchMethodException | SecurityException e) {
		throw new NbtApiException("Error while wrapping the Object " + object + " to it's NMS object!", e);
	}
}
 
Example 18
Source File: ConstructorInstanceFactory.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
public ConstructorInstanceFactory(final Constructor<T> constructor) {
    constructor.setAccessible(true);
    this.constructor = constructor;
}
 
Example 19
Source File: ReflectUtils.java    From juice with Apache License 2.0 4 votes vote down vote up
public static void makeAccessible(Constructor<?> ctor) {
    if((!Modifier.isPublic(ctor.getModifiers()) || !Modifier.isPublic(ctor.getDeclaringClass().getModifiers())) && !ctor.isAccessible()) {
        ctor.setAccessible(true);
    }
}
 
Example 20
Source File: NotPreferredMech.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] argv) throws Exception {

        // Generates a NegTokenInit mechTypes field, with an
        // unsupported mech as the preferred.
        DerOutputStream mech = new DerOutputStream();
        mech.write(new Oid("1.2.3.4").getDER());
        mech.write(GSSUtil.GSS_KRB5_MECH_OID.getDER());
        DerOutputStream mechTypeList = new DerOutputStream();
        mechTypeList.write(DerValue.tag_Sequence, mech);

        // Generates a NegTokenInit mechToken field for 1.2.3.4 mech
        GSSHeader h1 = new GSSHeader(new ObjectIdentifier("1.2.3.4"), 1);
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        h1.encode(bout);
        bout.write(new byte[1]);

        // Generates the NegTokenInit token
        Constructor<NegTokenInit> ctor = NegTokenInit.class.getDeclaredConstructor(
                byte[].class, BitArray.class, byte[].class, byte[].class);
        ctor.setAccessible(true);
        NegTokenInit initToken = ctor.newInstance(
                mechTypeList.toByteArray(),
                new BitArray(0),
                bout.toByteArray(),
                null);
        Method m = Class.forName("sun.security.jgss.spnego.SpNegoToken")
                .getDeclaredMethod("getEncoded");
        m.setAccessible(true);
        byte[] spnegoToken = (byte[])m.invoke(initToken);

        // and wraps it into a GSSToken
        GSSHeader h = new GSSHeader(
                new ObjectIdentifier(GSSUtil.GSS_SPNEGO_MECH_OID.toString()),
                spnegoToken.length);
        bout = new ByteArrayOutputStream();
        h.encode(bout);
        bout.write(spnegoToken);
        byte[] token = bout.toByteArray();

        // and feeds it to a GSS acceptor
        GSSManager man = GSSManager.getInstance();
        GSSContext ctxt = man.createContext((GSSCredential) null);
        token = ctxt.acceptSecContext(token, 0, token.length);
        NegTokenTarg targ = new NegTokenTarg(token);

        // Make sure it's a GO-ON message
        Method m2 = NegTokenTarg.class.getDeclaredMethod("getNegotiatedResult");
        m2.setAccessible(true);
        int negResult = (int)m2.invoke(targ);

        if (negResult != 1 /* ACCEPT_INCOMPLETE */) {
            throw new Exception("Not a continue");
        }
    }