List of usage examples for java.lang.reflect Constructor setAccessible
@Override @CallerSensitive public void setAccessible(boolean flag)
A SecurityException is also thrown if this object is a Constructor object for the class Class and flag is true.
From source file:org.jgentleframework.utils.ReflectUtils.java
/** * Make the given constructor accessible, explicitly setting it accessible * if necessary. The <code>setAccessible(true)</code> method is only called * when actually necessary, to avoid unnecessary conflicts with a JVM * SecurityManager (if active)./*from ww w. j a v a 2s.com*/ * * @param ctor * the constructor to make accessible * @see java.lang.reflect.Constructor#setAccessible(boolean) */ public static void makeAccessible(Constructor<?> ctor) { if (!Modifier.isPublic(ctor.getModifiers()) || !Modifier.isPublic(ctor.getDeclaringClass().getModifiers())) { ctor.setAccessible(true); } }
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 .j a v a 2s . c o m*/ return constructor.newInstance(); }
From source file:com.puppycrawl.tools.checkstyle.checks.SuppressWarningsHolderTest.java
@Test public void testIsSuppressedWithAllArgument() throws Exception { Class<?> entry = Class.forName("com.puppycrawl.tools.checkstyle.checks.SuppressWarningsHolder$Entry"); Constructor<?> entryConstr = entry.getDeclaredConstructor(String.class, int.class, int.class, int.class, int.class); entryConstr.setAccessible(true); Object entryInstance = entryConstr.newInstance("all", 100, 100, 350, 350); List<Object> entriesList = new ArrayList<>(); entriesList.add(entryInstance);/*from w ww. j a v a 2s .c om*/ ThreadLocal<?> threadLocal = mock(ThreadLocal.class); PowerMockito.doReturn(entriesList).when(threadLocal, "get"); SuppressWarningsHolder holder = new SuppressWarningsHolder(); Field entries = holder.getClass().getDeclaredField("ENTRIES"); entries.setAccessible(true); entries.set(holder, threadLocal); assertFalse(SuppressWarningsHolder.isSuppressed("SourceName", 100, 10)); assertTrue(SuppressWarningsHolder.isSuppressed("SourceName", 100, 150)); assertTrue(SuppressWarningsHolder.isSuppressed("SourceName", 200, 1)); }
From source file:org.codehaus.griffon.commons.AbstractGriffonClass.java
public Object newInstance() { try {//from ww w . ja va2s. co m Constructor<?> defaultConstructor = getClazz().getDeclaredConstructor(new Class[] {}); if (!defaultConstructor.isAccessible()) { defaultConstructor.setAccessible(true); } return defaultConstructor.newInstance(new Object[] {}); } catch (Exception e) { Throwable targetException = null; if (e instanceof InvocationTargetException) { targetException = ((InvocationTargetException) e).getTargetException(); } else { targetException = e; } throw new NewInstanceCreationException( "Could not create a new instance of class [" + getClazz().getName() + "]!", targetException); } }
From source file:com.puppycrawl.tools.checkstyle.checks.SuppressWarningsHolderTest.java
@Test public void testIsSuppressed() throws Exception { Class<?> entry = Class.forName("com.puppycrawl.tools.checkstyle.checks.SuppressWarningsHolder$Entry"); Constructor<?> entryConstructor = entry.getDeclaredConstructor(String.class, int.class, int.class, int.class, int.class); entryConstructor.setAccessible(true); Object entryInstance = entryConstructor.newInstance("MockEntry", 100, 100, 350, 350); List<Object> entriesList = new ArrayList<>(); entriesList.add(entryInstance);/*from www . j av a 2s.c o m*/ ThreadLocal<?> threadLocal = mock(ThreadLocal.class); PowerMockito.doReturn(entriesList).when(threadLocal, "get"); SuppressWarningsHolder holder = new SuppressWarningsHolder(); Field entries = holder.getClass().getDeclaredField("ENTRIES"); entries.setAccessible(true); entries.set(holder, threadLocal); assertFalse(SuppressWarningsHolder.isSuppressed("SourceName", 100, 10)); }
From source file:com.machinepublishers.jbrowserdriver.LaxCookieSpecProvider.java
@Override public CookieSpec create(final HttpContext context) { if (cookieSpec == null) { synchronized (this) { if (cookieSpec == null) { try { Constructor constructor = RFC2965Spec.class.getDeclaredConstructor(boolean.class, CommonCookieAttributeHandler[].class); constructor.setAccessible(true); final RFC2965Spec strict = (RFC2965Spec) constructor.newInstance(false, (Object) new CommonCookieAttributeHandler[] { new RFC2965VersionAttributeHandler(), new BasicPathHandler() { @Override public void validate(final Cookie cookie, final CookieOrigin origin) throws MalformedCookieException { // No validation } }, new PublicSuffixFilter(PublicSuffixDomainFilter .decorate(new RFC2965DomainAttributeHandler() { @Override public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException { // No validation } }, PublicSuffixMatcherLoader.getDefault())), new RFC2965PortAttributeHandler(), new BasicMaxAgeHandler(), new BasicSecureHandler(), new BasicCommentHandler(), new RFC2965CommentUrlAttributeHandler(), new RFC2965DiscardAttributeHandler() }); constructor = RFC2109Spec.class.getDeclaredConstructor(boolean.class, CommonCookieAttributeHandler[].class); constructor.setAccessible(true); final RFC2109Spec obsoleteStrict = (RFC2109Spec) constructor.newInstance(false, (Object) new CommonCookieAttributeHandler[] { new RFC2109VersionHandler(), new BasicPathHandler() { @Override public void validate(final Cookie cookie, final CookieOrigin origin) throws MalformedCookieException { // No validation } }, new PublicSuffixFilter( PublicSuffixDomainFilter.decorate(new RFC2109DomainHandler() { @Override public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException { // No validation } }, PublicSuffixMatcherLoader.getDefault())), new BasicMaxAgeHandler(), new BasicSecureHandler(), new BasicCommentHandler() }); constructor = NetscapeDraftSpec.class .getDeclaredConstructor(CommonCookieAttributeHandler[].class); constructor.setAccessible(true); final NetscapeDraftSpec netscapeDraft = (NetscapeDraftSpec) constructor .newInstance((Object) new CommonCookieAttributeHandler[] { new PublicSuffixFilter( PublicSuffixDomainFilter.decorate(new BasicDomainHandler() { @Override public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException { // No validation } }, PublicSuffixMatcherLoader.getDefault())), new BasicPathHandler() { @Override public void validate(final Cookie cookie, final CookieOrigin origin) throws MalformedCookieException { // No validation } }, new BasicSecureHandler(), new BasicCommentHandler(), new BasicExpiresHandler(DATE_PATTERNS) }); constructor = DefaultCookieSpec.class.getDeclaredConstructor(RFC2965Spec.class, RFC2109Spec.class, NetscapeDraftSpec.class); constructor.setAccessible(true); this.cookieSpec = (DefaultCookieSpec) constructor.newInstance(strict, obsoleteStrict, netscapeDraft); } catch (Throwable t) { Util.handleException(t); }//from w w w .j av a 2 s .c o m } } } return this.cookieSpec; }
From source file:com.fondesa.lyra.coder.DefaultCoderRetriever.java
/** * Retrieve a {@link StateCoder} from an annotation and the annotated class. * * @param saveState annotation obtained from the annotated field * @param annotatedFieldClass java class of the annotate field * @return not null coder used to serialize and deserialize the state {@link Bundle} * @throws CoderNotFoundException if the coder can't be found or is unsupported *//*from w ww.java 2 s. c o m*/ @NonNull @Override public StateCoder getCoder(@NonNull SaveState saveState, @NonNull Class<?> annotatedFieldClass) throws CoderNotFoundException { StateCoder stateCoder; // Get the coder class from the annotation. final Class<? extends StateCoder> stateSDClass = saveState.value(); if (stateSDClass == StateCoder.class) { // Get the coder from cache, if present. stateCoder = mCachedCoders.get(annotatedFieldClass); if (stateCoder != null) return stateCoder; // Get the coder if it's supported by default or throw a new CoderNotFoundException. stateCoder = StateCoderUtils.getBasicCoderForClass(annotatedFieldClass); // Put the coder in cache. mCachedCoders.put(annotatedFieldClass, stateCoder); } else { // A custom coder won't be cached to support multiple implementations for the same class. try { Constructor<? extends StateCoder> constructor = stateSDClass.getConstructor(); boolean accessible = constructor.isAccessible(); // If the constructor can't be accessed, it will be modified in accessible and will return inaccessible after. if (!accessible) { constructor.setAccessible(true); } // Creates the instance. stateCoder = constructor.newInstance(); if (!accessible) { constructor.setAccessible(false); } } catch (Exception e) { throw new RuntimeException("Cannot instantiate a " + StateCoder.class.getSimpleName() + " of class " + stateSDClass.getName()); } } return stateCoder; }
From source file:com.baidu.bjf.remoting.protobuf.IDLProxyObject.java
private IDLProxyObject doSetFieldValue(String fullField, String field, Object value, Object object, boolean useCache, Map<String, ReflectInfo> cachedFields) { Field f;//www . j a va2 s .c o m // check cache if (useCache) { ReflectInfo info = cachedFields.get(fullField); if (info != null) { setField(value, info.target, info.field); return this; } } int index = field.indexOf('.'); if (index != -1) { String parent = field.substring(0, index); String sub = field.substring(index + 1); try { f = FieldUtils.findField(object.getClass(), parent); if (f == null) { throw new RuntimeException( "No field '" + parent + "' found at class " + object.getClass().getName()); } Class<?> type = f.getType(); f.setAccessible(true); Object o = f.get(object); if (o == null) { boolean memberClass = type.isMemberClass(); if (memberClass && Modifier.isStatic(type.getModifiers())) { Constructor<?> constructor = type.getConstructor(new Class[0]); constructor.setAccessible(true); o = constructor.newInstance(new Object[0]); } else if (memberClass) { Constructor<?> constructor = type.getConstructor(new Class[] { object.getClass() }); constructor.setAccessible(true); o = constructor.newInstance(new Object[] { object }); } else { o = type.newInstance(); } f.set(object, o); } return put(fullField, sub, value, o); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } f = FieldUtils.findField(object.getClass(), field); if (f == null) { throw new RuntimeException("No field '" + field + "' found at class " + object.getClass().getName()); } if (useCache && !cachedFields.containsKey(fullField)) { cachedFields.put(fullField, new ReflectInfo(f, object)); } setField(value, object, f); return this; }
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); constructor.newInstance();/*from w w w . j a v a 2 s.c o m*/ }
From source file:com.scaleoutsoftware.soss.hserver.hadoop.ReducerWrapperMapred.java
public ReducerWrapperMapred(HServerInvocationParameters invocationParameters, int hadoopPartition, int appId, int region, boolean sort) throws IOException, ClassNotFoundException, InterruptedException { this.invocationParameters = invocationParameters; JobConf jobConf = new JobConf((Configuration) invocationParameters.getConfiguration()); //Clone JobConf, so the temporary settings do not pollute other tasks LOG.info("Starting reducer:" + HadoopInvocationParameters.dumpConfiguration(jobConf)); JobID jobID = (JobID) invocationParameters.getJobId(); this.hadoopPartition = hadoopPartition; hadoopVersionSpecificCode = HadoopVersionSpecificCode.getInstance(invocationParameters.getHadoopVersion(), jobConf);/*from w ww .j av a 2 s .c om*/ TaskAttemptID taskAttemptID = TaskAttemptID .downgrade(hadoopVersionSpecificCode.createTaskAttemptId(jobID, false, hadoopPartition)); updateJobConf(jobConf, taskAttemptID, region); context = hadoopVersionSpecificCode.createTaskAttemptContextMapred(jobConf, taskAttemptID); reducer = (org.apache.hadoop.mapred.Reducer<INKEY, INVALUE, OUTKEY, OUTVALUE>) ReflectionUtils .newInstance(jobConf.getReducerClass(), jobConf); reducer.configure(jobConf); OutputFormat outputFormat = jobConf.getOutputFormat(); FileSystem fs = FileSystem.get(jobConf); recordWriter = (org.apache.hadoop.mapred.RecordWriter<OUTKEY, OUTVALUE>) outputFormat.getRecordWriter(fs, jobConf, getOutputName(hadoopPartition), Reporter.NULL); committer = jobConf.getOutputCommitter(); //Create task object so it can handle file format initialization //The ReduceTask is private in the Hadoop 1.x so we have to go through reflection. try { Class reduceTask = Class.forName("org.apache.hadoop.mapred.ReduceTask"); Constructor reduceTaskConstructor = reduceTask.getDeclaredConstructor(String.class, TaskAttemptID.class, int.class, int.class, int.class); reduceTaskConstructor.setAccessible(true); Task task = (Task) reduceTaskConstructor.newInstance(null, taskAttemptID, hadoopPartition, 0, 0); task.setConf(jobConf); task.initialize(jobConf, jobID, Reporter.NULL, false); } catch (Exception e) { throw new IOException("Cannot initialize ReduceTask", e); } committer.setupTask(context); Class<INKEY> keyClass = (Class<INKEY>) jobConf.getMapOutputKeyClass(); WritableSerializerDeserializer<INKEY> firstKeySerializer = new WritableSerializerDeserializer<INKEY>( keyClass, null); WritableSerializerDeserializer<INKEY> secondKeySerializer = new WritableSerializerDeserializer<INKEY>( keyClass, null); Class<INVALUE> valueClass = (Class<INVALUE>) jobConf.getMapOutputValueClass(); WritableSerializerDeserializer<INVALUE> valueSerializer = new WritableSerializerDeserializer<INVALUE>( valueClass, null); DataGridReaderParameters<INKEY, INVALUE> params = new DataGridReaderParameters<INKEY, INVALUE>(region, appId, HServerParameters.getSetting(REDUCE_USEMEMORYMAPPEDFILES, jobConf) > 0, firstKeySerializer, valueSerializer, invocationParameters.getSerializationMode(), secondKeySerializer, keyClass, valueClass, sort, HServerParameters.getSetting(REDUCE_CHUNKSTOREADAHEAD, jobConf), 1024 * HServerParameters.getSetting(REDUCE_INPUTCHUNKSIZE_KB, jobConf), HServerParameters.getSetting(REDUCE_CHUNKREADTIMEOUT, jobConf)); transport = DataGridChunkedCollectionReader.getGridReader(params); outputCollector = new OutputCollector<OUTKEY, OUTVALUE>() { @Override public void collect(OUTKEY outkey, OUTVALUE outvalue) throws IOException { recordWriter.write(outkey, outvalue); } }; }