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

The following examples show how to use java.lang.reflect.Constructor#isAccessible() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: sarl   File: SerializableProxy.java    License: Apache License 2.0 6 votes vote down vote up
/** This function enables to deserialize an instance of this proxy.
 * @throws ObjectStreamException if the deserialization fails
 */
private Object readResolve() throws ObjectStreamException {
	Constructor<?> compatible = null;
	for (final Constructor<?> candidate : this.proxyType.getDeclaredConstructors()) {
		if (candidate != null && isCompatible(candidate)) {
			if (compatible != null) {
				throw new IllegalStateException();
			}
			compatible = candidate;
		}
	}
	if (compatible != null) {
		if (!compatible.isAccessible()) {
			compatible.setAccessible(true);
		}
		try {
			final Object[] arguments = new Object[this.values.length + 1];
			System.arraycopy(this.values, 0, arguments, 1, this.values.length);
			return compatible.newInstance(arguments);
		} catch (Exception exception) {
			throw new WriteAbortedException(exception.getLocalizedMessage(), exception);
		}
	}
	throw new InvalidClassException("compatible constructor not found"); //$NON-NLS-1$
}
 
Example 2
public boolean write(Type type, Object value, NodeMap<OutputNode> node, Map map) throws Exception {
   Convert convert = type.getAnnotation(Convert.class);
   OutputNode parent = node.getNode();
   
   if(convert != null) {
      Class<? extends Converter> converterClass = convert.value();
      Constructor<? extends Converter> converterConstructor = converterClass.getDeclaredConstructor();
      
      if(!converterConstructor.isAccessible()) {
         converterConstructor.setAccessible(true);
      }
      Converter converter = converterConstructor.newInstance();
      converter.write(parent, value);
      return true;
   }
   return strategy.write(type, value, node, map);
}
 
Example 3
Source Project: morpheus   File: TestUtilityClassUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that a utility class is well defined.
 * @param clazz utility class to verify.
 */
public static void assertUtilityClassWellDefined(final Class<?> clazz)
    throws NoSuchMethodException, InvocationTargetException, InstantiationException,
    IllegalAccessException {
  assertTrue("Class must be final", Modifier.isFinal(clazz.getModifiers()));
  assertEquals("There must be only one constructor", 1, clazz.getDeclaredConstructors().length);
  final Constructor<?> constructor = clazz.getDeclaredConstructor();
  if (constructor.isAccessible() || !Modifier.isPrivate(constructor.getModifiers())) {
    Assert.fail("Constructor is not private");
  }
  constructor.setAccessible(true);
  constructor.newInstance();
  constructor.setAccessible(false);
  for (final Method method : clazz.getMethods()) {
    if (!Modifier.isStatic(method.getModifiers()) && method.getDeclaringClass().equals(clazz)) {
      Assert.fail("There exists a non-static method: " + method);
    }
  }
}
 
Example 4
Source Project: gemfirexd-oss   File: DSFIDFactory.java    License: Apache License 2.0 6 votes vote down vote up
static void registerDSFID(int dsfid,
    Class dsfidClass) {
  try {
    Constructor<?> cons = dsfidClass.getConstructor((Class[])null);
    cons.setAccessible(true);
    if (!cons.isAccessible()) {
      throw new InternalGemFireError("default constructor not accessible "
          + "for DSFID=" + dsfid + ": " + dsfidClass);
    }
    if (dsfid >= Byte.MIN_VALUE && dsfid <= Byte.MAX_VALUE) {
      dsfidMap[dsfid + Byte.MAX_VALUE + 1] = cons;
    }
    else {
      dsfidMap2.put(dsfid, cons);
    }
  } catch (NoSuchMethodException nsme) {
    throw new InternalGemFireError(nsme);
  }
}
 
Example 5
Source Project: tomee   File: JuliLogStreamFactory.java    License: Apache License 2.0 6 votes vote down vote up
private static void setRootLogger(final OpenEJBLogManager value) {
    try { // if we don't do it - which is done in static part of the LogManager - we couldn't log user info when force-reload is to true
        final Class<?> rootLoggerClass = ClassLoader.getSystemClassLoader().loadClass("java.util.logging.LogManager$RootLogger");
        final Constructor<?> cons = rootLoggerClass.getDeclaredConstructor(LogManager.class);
        final boolean acc = cons.isAccessible();
        if (!acc) {
            cons.setAccessible(true);
        }
        final Logger rootLogger = Logger.class.cast(cons.newInstance(value));
        try {
            Reflections.set(value, "rootLogger", rootLogger);
        } finally {
            cons.setAccessible(acc);
        }
        value.addLogger(rootLogger);
        Reflections.invokeByReflection(Reflections.get(value, "systemContext"), "addLocalLogger", new Class<?>[]{Logger.class}, new Object[]{rootLogger});
        Reflections.invokeByReflection(Logger.getGlobal(), "setLogManager", new Class<?>[]{LogManager.class}, new Object[]{value});
        value.addLogger(Logger.getGlobal());
    } catch (final Throwable e) {
        // no-op
    }
}
 
Example 6
Source Project: reflection-util   File: ClassUtils.java    License: Apache License 2.0 5 votes vote down vote up
static <T> T createInstance(Constructor<T> constructor) throws ReflectiveOperationException {
	boolean accessible = constructor.isAccessible();
	try {
		if (!accessible) {
			constructor.setAccessible(true);
		}
		return constructor.newInstance();
	} finally {
		if (!accessible) {
			constructor.setAccessible(false);
		}
	}
}
 
Example 7
Source Project: asciidoctorj   File: SecurityActions.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a new instance by finding a constructor that matches the argumentTypes signature
 * using the arguments for instantiation.
 *
 * @param implClass Full classname of class to create
 * @param argumentTypes The constructor argument types
 * @param arguments The constructor arguments
 * @return a new instance
 * @throws IllegalArgumentException if className, argumentTypes, or arguments are null
 * @throws RuntimeException if any exceptions during creation
 * @author <a href="mailto:[email protected]">Aslak Knutsen</a>
 * @author <a href="mailto:[email protected]">ALR</a>
 */
static <T> T newInstance(final Class<T> implClass, final Class<?>[] argumentTypes, final Object[] arguments)
{
    if (implClass == null)
    {
        throw new IllegalArgumentException("ImplClass must be specified");
    }
    if (argumentTypes == null)
    {
        throw new IllegalArgumentException("ArgumentTypes must be specified. Use empty array if no arguments");
    }
    if (arguments == null)
    {
        throw new IllegalArgumentException("Arguments must be specified. Use empty array if no arguments");
    }
    final T obj;
    try
    {
        Constructor<T> constructor = getConstructor(implClass, argumentTypes);
        if(!constructor.isAccessible()) {
            constructor.setAccessible(true);
        }
        obj = constructor.newInstance(arguments);
    }
    catch (Exception e)
    {
        throw new RuntimeException("Could not create new instance of " + implClass, e);
    }

    return obj;
}
 
Example 8
Source Project: quarkus   File: Reflections.java    License: Apache License 2.0 5 votes vote down vote up
public static Object newInstance(Class<?> clazz, Class<?>[] parameterTypes, Object[] args) {
    Constructor<?> constructor = findConstructor(clazz, parameterTypes);
    if (constructor != null) {
        if (!constructor.isAccessible()) {
            constructor.setAccessible(true);
        }
        try {
            return constructor.newInstance(args);
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            throw new RuntimeException("Cannot invoke constructor: " + clazz.getName(), e);
        }
    }
    throw new RuntimeException(
            "No " + clazz.getName() + "constructor found for params: " + Arrays.toString(parameterTypes));
}
 
Example 9
Source Project: simplexml   File: VersionTest.java    License: Apache License 2.0 5 votes vote down vote up
public Object getValue()  {
   try {
      Constructor method = type.getDeclaredConstructor();
   
      if(!method.isAccessible()) {
         method.setAccessible(true);              
      }
      return method.newInstance();   
   }catch(Exception e) {
      throw new RuntimeException(e);
   }
}
 
Example 10
Source Project: FuzzDroid   File: DecisionMakerConfig.java    License: Apache License 2.0 5 votes vote down vote up
private boolean registerProgressMetrics() {
	Set<String> registeredMetrics = getProgressMetricNames();
	for(String registeredMetricsClassName : registeredMetrics)
		if (!registeredMetricsClassName.startsWith("%")) {
			try{						
				Class<?> metricClass = Class.forName(registeredMetricsClassName);
				Constructor<?> defaultConstructor = metricClass.getConstructor(Collection.class, InfoflowCFG.class);
				defaultConstructor.isAccessible();
				Object constructorObject = defaultConstructor.newInstance(allTargetLocations, backwardsCFG);
				if(!(constructorObject instanceof IProgressMetric))
					throw new RuntimeException("There is a problem with the registered metric in the files/metricsNames.txt file!");
				IProgressMetric metric = (IProgressMetric)constructorObject;
				LoggerHelper.logEvent(MyLevel.ANALYSIS, "[METRIC-TYPE] " + registeredMetricsClassName);
				
				//currently, there can be only a single target
				if(allTargetLocations.size() != 1)
					throw new RuntimeException("There can be only 1 target location per run");
				Unit target = allTargetLocations.iterator().next();
				if(backwardsCFG.getMethodOf(target) != null) {													
					metric.setCurrentTargetLocation(target);
				
					//initialize the metric, otherwise it is empty!
					metric.initalize();										
					progressMetrics.add(metric);
				}
				else{
					LoggerHelper.logEvent(MyLevel.LOGGING_POINT, "target is not statically reachable!");
					return false;
				}
			}
			catch(Exception ex) {
				LoggerHelper.logEvent(MyLevel.EXCEPTION_ANALYSIS, ex.getMessage());
				ex.printStackTrace();
				System.exit(-1);
			}				
		}
	return true;
}
 
Example 11
Source Project: letv   File: ServcesManager.java    License: 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 12
Source Project: letv   File: f.java    License: Apache License 2.0 5 votes vote down vote up
private <T> ae<T> a(Class<? super T> cls) {
    try {
        Constructor declaredConstructor = cls.getDeclaredConstructor(new Class[0]);
        if (!declaredConstructor.isAccessible()) {
            declaredConstructor.setAccessible(true);
        }
        return new l(this, declaredConstructor);
    } catch (NoSuchMethodException e) {
        return null;
    }
}
 
Example 13
public Constructor0(final Constructor constructor) {
    this.constructor = constructor;
    if (!constructor.isAccessible()) {
        constructor.setAccessible(true);
    }
}
 
Example 14
private void handleCreateServiceOne(Context hostContext, Intent stubIntent, ServiceInfo info) throws Exception {
    //            CreateServiceData data = new CreateServiceData();
    //            data.token = fakeToken;// IBinder
    //            data.info =; //ServiceInfo
    //            data.compatInfo =; //CompatibilityInfo
    //            data.intent =; //Intent
    //            activityThread.handleCreateServiceOne(data);
    //            service = activityThread.mTokenServices.get(fakeToken);
    //            activityThread.mTokenServices.remove(fakeToken);
    ResolveInfo resolveInfo = hostContext.getPackageManager().resolveService(stubIntent, 0);
    ServiceInfo stubInfo = resolveInfo != null ? resolveInfo.serviceInfo : null;
    PluginManager.getInstance().reportMyProcessName(stubInfo.processName, info.processName, info.packageName);
    PluginProcessManager.preLoadApk(hostContext, info);
    Object activityThread = ActivityThreadCompat.currentActivityThread();
    IBinder fakeToken = new MyFakeIBinder();
    Class CreateServiceData = Class.forName(ActivityThreadCompat.activityThreadClass().getName() + "$CreateServiceData");
    Constructor init = CreateServiceData.getDeclaredConstructor();
    if (!init.isAccessible()) {
        init.setAccessible(true);
    }
    Object data = init.newInstance();

    FieldUtils.writeField(data, "token", fakeToken);
    FieldUtils.writeField(data, "info", info);
    if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) {
        FieldUtils.writeField(data, "compatInfo", CompatibilityInfoCompat.DEFAULT_COMPATIBILITY_INFO());
    }

    Method method = activityThread.getClass().getDeclaredMethod("handleCreateService", CreateServiceData);
    if (!method.isAccessible()) {
        method.setAccessible(true);
    }
    method.invoke(activityThread, data);
    Object mService = FieldUtils.readField(activityThread, "mServices");
    Service service = (Service) MethodUtils.invokeMethod(mService, "get", fakeToken);
    MethodUtils.invokeMethod(mService, "remove", fakeToken);
    mTokenServices.put(fakeToken, service);
    mNameService.put(info.name, service);


    if (stubInfo != null) {
        PluginManager.getInstance().onServiceCreated(stubInfo, info);
    }
}
 
Example 15
@SuppressWarnings("unchecked")
@NotNull
private static <T> T parseObject(@NotNull Class<T> type, @Nullable SvnServerParser tokenParser) throws IOException {
  if (tokenParser != null && tokenParser.readItem(ListBeginToken.class) == null)
    tokenParser = null;

  final int depth = getDepth(tokenParser);

  if (type.isArray()) {
    final List<Object> result = new ArrayList<>();

    if (tokenParser != null) {
      while (true) {
        final Object element = parse(type.getComponentType(), tokenParser);
        if (getDepth(tokenParser) < depth)
          break;

        result.add(element);
      }
    }

    return (T) result.toArray((Object[]) Array.newInstance(type.getComponentType(), result.size()));
  }

  final Constructor<?>[] ctors = type.getDeclaredConstructors();
  if (ctors.length != 1) {
    throw new IllegalStateException("Can't find parser ctor for object: " + type.getName());
  }
  final Constructor<?> ctor = ctors[0];
  final Parameter[] ctorParams = ctor.getParameters();
  Object[] params = new Object[ctorParams.length];
  for (int i = 0; i < params.length; ++i) {
    params[i] = parse(ctorParams[i].getType(), getDepth(tokenParser) == depth ? tokenParser : null);
  }
  while (tokenParser != null && getDepth(tokenParser) >= depth) {
      tokenParser.readToken();
  }

  try {
    if (!ctor.isAccessible())
      ctor.setAccessible(true);

    return (T) ctor.newInstance(params);
  } catch (ReflectiveOperationException e) {
    throw new IllegalStateException(e);
  }
}
 
Example 16
Source Project: java-technology-stack   File: ReflectionUtils.java    License: MIT License 3 votes vote down vote up
/**
 * Make the given constructor accessible, explicitly setting it accessible
 * if necessary. The {@code setAccessible(true)} method is only called
 * when actually necessary, to avoid unnecessary conflicts with a JVM
 * SecurityManager (if active).
 * @param ctor the constructor to make accessible
 * @see java.lang.reflect.Constructor#setAccessible
 */
@SuppressWarnings("deprecation")  // on JDK 9
public static void makeAccessible(Constructor<?> ctor) {
	if ((!Modifier.isPublic(ctor.getModifiers()) ||
			!Modifier.isPublic(ctor.getDeclaringClass().getModifiers())) && !ctor.isAccessible()) {
		ctor.setAccessible(true);
	}
}
 
Example 17
Source Project: super-cloudops   File: ReflectionUtils2.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Make the given constructor accessible, explicitly setting it accessible
 * if necessary. The {@code setAccessible(true)} method is only called when
 * actually necessary, to avoid unnecessary conflicts with a JVM
 * SecurityManager (if active).
 * 
 * @param ctor
 *            the constructor to make accessible
 * @see java.lang.reflect.Constructor#setAccessible
 */
public static void makeAccessible(Constructor<?> ctor) {
	if ((!Modifier.isPublic(ctor.getModifiers()) || !Modifier.isPublic(ctor.getDeclaringClass().getModifiers()))
			&& !ctor.isAccessible()) {
		ctor.setAccessible(true);
	}
}
 
Example 18
Source Project: simplexml   File: LabelExtractor.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Creates a constructor that can be used to instantiate the label
 * used to represent the specified annotation. The constructor
 * created by this method takes two arguments, a contact object 
 * and an <code>Annotation</code> of the type specified.
 * 
 * @param label the XML annotation representing the label
 * 
 * @return returns a constructor for instantiating the label 
 */
private Constructor getConstructor(Annotation label) throws Exception {
   LabelBuilder builder = getBuilder(label);
   Constructor factory = builder.getConstructor();
   
   if(!factory.isAccessible()) {
      factory.setAccessible(true);
   }
   return factory;
}
 
Example 19
/**
 * Make the given constructor accessible, explicitly setting it accessible if necessary. The
 * {@code setAccessible(true)} method is only called when actually necessary, to avoid unnecessary conflicts with a
 * JVM SecurityManager (if active).
 * 
 * @param ctor
 *        the constructor to make accessible
 * @see java.lang.reflect.Constructor#setAccessible
 */
public static void makeAccessible(Constructor<?> ctor) {
	if ((!Modifier.isPublic(ctor.getModifiers()) || !Modifier.isPublic(ctor.getDeclaringClass().getModifiers()))
			&& !ctor.isAccessible()) {
		ctor.setAccessible(true);
	}
}
 
Example 20
/**
 * Make the given constructor accessible, explicitly setting it accessible
 * if necessary. The {@code setAccessible(true)} method is only called
 * when actually necessary, to avoid unnecessary conflicts with a JVM
 * SecurityManager (if active).
 * @param ctor the constructor to make accessible
 * @see java.lang.reflect.Constructor#setAccessible
 */
public static void makeAccessible(Constructor<?> ctor) {
	if ((!Modifier.isPublic(ctor.getModifiers()) ||
			!Modifier.isPublic(ctor.getDeclaringClass().getModifiers())) && !ctor.isAccessible()) {
		ctor.setAccessible(true);
	}
}