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.omnaest.utils.reflection.ReflectionUtils.java
/** * Creates a new instance of a given {@link Class} using a constructor which has the same parameter signature as the provided * arguments. <br>/*from w w w .j a v a2 s . c om*/ * <br> * Primitive arguments will be matched to their java wrapper types.<br> * <br> * This method never throws an {@link Exception} instead null is returned. * * @see #newInstanceByValueOf(Class, Object...) * @param type * {@link Class} * @param arguments */ public static <B> B newInstanceOf(Class<? extends B> type, Object... arguments) { // B retval = null; // if (type != null) { // try { // Constructor<? extends B> constructor = constructorFor(type, arguments); constructor.setAccessible(true); // retval = constructor.newInstance(arguments); } catch (Exception e) { } } // return retval; }
From source file:eu.tripledframework.eventstore.infrastructure.ReflectionObjectConstructor.java
private T createInstance(DomainEvent event) { Constructor constructor = getEventHandlerConstructor(event); if (constructor == null) { throw new AggregateRootReconstructionException( String.format("Could not find a suitable constructor for event %s", event)); }//from ww w.j a v a2 s.c o m try { constructor.setAccessible(true); Object[] parameters = getParametersValues(constructor.getParameterAnnotations(), event); return (T) constructor.newInstance(parameters); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new AggregateRootReconstructionException( String.format("Could not create object using constructor %s", constructor), e); } }
From source file:org.blocks4j.reconf.client.config.update.ConfigurationRepositoryUpdater.java
private void sync(Class<? extends RuntimeException> cls) { LoggerHolder.getLog().info(msg.format("sync.start", getName())); List<ConfigurationUpdater> toExecute = new ArrayList<ConfigurationUpdater>(); CountDownLatch latch = new CountDownLatch(data.getAll().size()); Map<Method, ConfigurationItemUpdateResult> updateAtomic = new ConcurrentHashMap<Method, ConfigurationItemUpdateResult>(); try {// ww w . j a va 2 s . c o m for (MethodConfiguration config : data.getAll()) { toExecute.add(locator.configurationUpdaterFactory().syncRemote(updateAtomic, config, latch)); } for (Thread thread : toExecute) { thread.start(); } waitFor(latch); } catch (Exception ignored) { LoggerHolder.getLog().error(msg.format("sync.error", getName()), ignored); } finally { interruptAll(toExecute); } if (ConfigurationItemUpdateResult.countSuccess(updateAtomic.values()) != data.getAll().size()) { String error = msg.format("sync.error", getName()); try { Constructor<?> constructor = null; constructor = cls.getConstructor(String.class); constructor.setAccessible(true); throw cls.cast(constructor.newInstance(error)); } catch (NoSuchMethodException ignored) { throw new UpdateConfigurationRepositoryException(error); } catch (InvocationTargetException ignored) { throw new UpdateConfigurationRepositoryException(error); } catch (InstantiationException ignored) { throw new UpdateConfigurationRepositoryException(error); } catch (IllegalAccessException ignored) { throw new UpdateConfigurationRepositoryException(error); } } finishSync(updateAtomic); Notifier.notify(listeners, toExecute, getName()); LoggerHolder.getLog().info(msg.format("sync.end", getName())); }
From source file:org.apache.hadoop.hbase.thrift2.client.ThriftConnection.java
public ThriftConnection(Configuration conf, ExecutorService pool, final User user) throws IOException { this.conf = conf; this.user = user; this.host = conf.get(Constants.HBASE_THRIFT_SERVER_NAME); this.port = conf.getInt(Constants.HBASE_THRIFT_SERVER_PORT, -1); Preconditions.checkArgument(port > 0); Preconditions.checkArgument(host != null); this.isFramed = conf.getBoolean(Constants.FRAMED_CONF_KEY, Constants.FRAMED_CONF_DEFAULT); this.isCompact = conf.getBoolean(Constants.COMPACT_CONF_KEY, Constants.COMPACT_CONF_DEFAULT); this.operationTimeout = conf.getInt(HConstants.HBASE_CLIENT_OPERATION_TIMEOUT, HConstants.DEFAULT_HBASE_CLIENT_OPERATION_TIMEOUT); this.connectTimeout = conf.getInt(SOCKET_TIMEOUT_CONNECT, DEFAULT_SOCKET_TIMEOUT_CONNECT); String className = conf.get(Constants.HBASE_THRIFT_CLIENT_BUIDLER_CLASS, DefaultThriftClientBuilder.class.getName()); try {//from ww w . j ava 2 s .c o m Class<?> clazz = Class.forName(className); Constructor<?> constructor = clazz.getDeclaredConstructor(ThriftConnection.class); constructor.setAccessible(true); clientBuilder = (ThriftClientBuilder) constructor.newInstance(this); } catch (Exception e) { throw new IOException(e); } }
From source file:ae.config.Project.java
private ActiveEntity loadModelDefinitionAt(final Class<?> aClass) { assert aClass != null : "aClass is null"; final Object declaredModel; final Constructor<?> constructor; try {// w ww . j av a2 s . c om constructor = aClass.getDeclaredConstructor(getClass()); } catch (final SecurityException e) { throw new IllegalStateException(e); } catch (final NoSuchMethodException e) { throw new IllegalStateException(e); } constructor.setAccessible(true); try { declaredModel = constructor.newInstance(this); } catch (final InstantiationException e) { throw new IllegalStateException(e); } catch (final IllegalAccessException e) { throw new IllegalStateException(e); } catch (final InvocationTargetException e) { throw new IllegalStateException(e); } return (ActiveEntity) declaredModel; }
From source file:org.silverpeas.core.test.extention.SilverTestEnv.java
private <T> T instantiate(final Class<? extends T> beanType) { T bean;/*from w w w . jav a2s. co m*/ try { Constructor<? extends T> constructor = beanType.getDeclaredConstructor(); constructor.setAccessible(true); bean = constructor.newInstance(); } catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) { bean = null; } return bean; }
From source file:org.cruk.genologics.api.GenologicsAPIPaginatedBatchTest.java
@Test public void testMultipageFetchListSome() throws Exception { // Note - reusing the files from above means that the subsequent pages // with have "&projectname=Run+1030" as part of the URL. This can be ignored // for this test. // Part one - mock the rest template to return the already parsed objects. RestOperations restMock = EasyMock.createStrictMock(RestOperations.class); EasyMock.expect(restMock.getForEntity("http://lims.cri.camres.org:8080/api/v2/samples?start-index=0", Samples.class)).andReturn(response1).once(); EasyMock.expect(restMock.getForEntity( new URI("http://lims.cri.camres.org:8080/api/v2/samples?start-index=500&projectname=Run+1030"), Samples.class)).andReturn(response2).once(); // Should get as far as response 3 in this test. GenologicsAPIImpl localApi = context.getBean("genologicsAPI", GenologicsAPIImpl.class); localApi.setRestClient(restMock);/*from w ww .ja v a 2s. c om*/ localApi.setServer(new URL("http://lims.cri.camres.org:8080")); EasyMock.replay(restMock); List<LimsLink<Sample>> links = localApi.listSome(Sample.class, 0, 750); EasyMock.verify(restMock); assertEquals("Expected 750 sample links returned", 750, links.size()); // Part two - mock the HTTP client and request factory to ensure that the URIs are // being presented as expected without character cludging. HttpContext httpContext = HttpClientContext.create(); HttpClient mockHttpClient = EasyMock.createMock(HttpClient.class); ClientHttpRequestFactory mockRequestFactory = EasyMock.createMock(ClientHttpRequestFactory.class); RestTemplate restTemplate = context.getBean("genologicsRestTemplate", RestTemplate.class); restTemplate.setRequestFactory(mockRequestFactory); localApi.setHttpClient(mockHttpClient); localApi.setRestClient(restTemplate); URI pageOne = new URI("http://lims.cri.camres.org:8080/api/v2/samples?start-index=0"); URI pageTwo = new URI( "http://lims.cri.camres.org:8080/api/v2/samples?start-index=500&projectname=Run+1030"); HttpGet getOne = new HttpGet(pageOne); HttpGet getTwo = new HttpGet(pageTwo); HttpResponse responseOne = createMultipageFetchResponse(pageFiles[0]); HttpResponse responseTwo = createMultipageFetchResponse(pageFiles[1]); Class<?> requestClass = Class.forName("org.springframework.http.client.HttpComponentsClientHttpRequest"); Constructor<?> constructor = requestClass.getDeclaredConstructor(HttpClient.class, HttpUriRequest.class, HttpContext.class); constructor.setAccessible(true); ClientHttpRequest reqOne = (ClientHttpRequest) constructor.newInstance(mockHttpClient, getOne, httpContext); ClientHttpRequest reqTwo = (ClientHttpRequest) constructor.newInstance(mockHttpClient, getTwo, httpContext); EasyMock.expect(mockRequestFactory.createRequest(pageOne, HttpMethod.GET)).andReturn(reqOne).once(); EasyMock.expect(mockRequestFactory.createRequest(pageTwo, HttpMethod.GET)).andReturn(reqTwo).once(); EasyMock.expect(mockHttpClient.execute(getOne, httpContext)).andReturn(responseOne).once(); EasyMock.expect(mockHttpClient.execute(getTwo, httpContext)).andReturn(responseTwo).once(); EasyMock.replay(mockHttpClient, mockRequestFactory); links = localApi.listSome(Sample.class, 0, 750); EasyMock.verify(mockHttpClient, mockRequestFactory); assertEquals("Expected 750 sample links returned", 750, links.size()); }
From source file:code.elix_x.excore.utils.nbt.mbt.encoders.NBTClassEncoder.java
@Override public Object fromNBT(MBT mbt, NBTTagCompound nbt, Class clazz, Class... tsclasses) { try {// www . j a v a 2 s . c om Constructor constructor; if (encodeClass) clazz = Class.forName(nbt.getString(CLASS)); try { constructor = clazz.getConstructor(); } catch (NoSuchMethodException e) { constructor = clazz.getDeclaredConstructor(); } constructor.setAccessible(true); Object o = constructor.newInstance(); populate(mbt, nbt, o); return o; } catch (InstantiationException e) { throw Throwables.propagate(e); } catch (IllegalAccessException e) { throw Throwables.propagate(e); } catch (NoSuchMethodException e) { throw Throwables.propagate(e); } catch (SecurityException e) { throw Throwables.propagate(e); } catch (IllegalArgumentException e) { throw Throwables.propagate(e); } catch (InvocationTargetException e) { throw Throwables.propagate(e); } catch (ClassNotFoundException e) { throw Throwables.propagate(e); } }
From source file:de.matzefratze123.heavyspleef.core.flag.FlagRegistry.java
public void registerFlag(Class<? extends AbstractFlag<?>> clazz) { Validate.notNull(clazz, "clazz cannot be null"); Validate.isTrue(!registeredFlagsMap.containsValue(clazz), "Cannot register flag twice"); /* Check if the class provides the required Flag annotation */ Validate.isTrue(clazz.isAnnotationPresent(Flag.class), "Flag-Class must be annotated with the @Flag annotation"); Flag flagAnnotation = clazz.getAnnotation(Flag.class); String name = flagAnnotation.name(); Validate.isTrue(!name.isEmpty(),// w ww. ja v a 2 s . c o m "name() of annotation of flag for class " + clazz.getCanonicalName() + " cannot be empty"); /* Generate a path */ StringBuilder pathBuilder = new StringBuilder(); Flag parentFlagData = flagAnnotation; do { pathBuilder.insert(0, parentFlagData.name()); Class<? extends AbstractFlag<?>> parentFlagClass = parentFlagData.parent(); parentFlagData = parentFlagClass.getAnnotation(Flag.class); if (parentFlagData != null && parentFlagClass != NullFlag.class) { pathBuilder.insert(0, FLAG_PATH_SEPERATOR); } } while (parentFlagData != null); String path = pathBuilder.toString(); /* Check for name collides */ for (String flagPath : registeredFlagsMap.primaryKeySet()) { if (flagPath.equalsIgnoreCase(path)) { throw new IllegalArgumentException( "Flag " + clazz.getName() + " collides with " + registeredFlagsMap.get(flagPath).getName()); } } /* Check if the class can be instantiated */ try { Constructor<? extends AbstractFlag<?>> constructor = clazz.getDeclaredConstructor(); //Make the constructor accessible for future uses constructor.setAccessible(true); } catch (NoSuchMethodException | SecurityException e) { throw new IllegalArgumentException("Flag-Class must provide an empty constructor"); } HookManager hookManager = heavySpleef.getHookManager(); boolean allHooksPresent = true; for (HookReference ref : flagAnnotation.depend()) { if (!hookManager.getHook(ref).isProvided()) { allHooksPresent = false; } } if (allHooksPresent) { for (Method method : clazz.getDeclaredMethods()) { if (!method.isAnnotationPresent(FlagInit.class)) { continue; } if ((method.getModifiers() & Modifier.STATIC) == 0) { throw new IllegalArgumentException("Flag initialization method " + method.getName() + " in type " + clazz.getCanonicalName() + " is not declared as static"); } queuedInitMethods.add(method); } if (flagAnnotation.hasCommands()) { CommandManager manager = heavySpleef.getCommandManager(); manager.registerSpleefCommands(clazz); } } registeredFlagsMap.put(path, flagAnnotation, clazz); }
From source file:org.cruk.genologics.api.GenologicsAPIPaginatedBatchTest.java
@Test public void testMultipageFetchFind() throws Exception { // Part one - mock the rest template to return the already parsed objects. RestOperations restMock = EasyMock.createStrictMock(RestOperations.class); EasyMock.expect(restMock.getForEntity("http://lims.cri.camres.org:8080/api/v2/samples?projectname=Run 1030", Samples.class)).andReturn(response1).once(); EasyMock.expect(restMock.getForEntity( new URI("http://lims.cri.camres.org:8080/api/v2/samples?start-index=500&projectname=Run+1030"), Samples.class)).andReturn(response2).once(); EasyMock.expect(restMock.getForEntity( new URI("http://lims.cri.camres.org:8080/api/v2/samples?start-index=1000&projectname=Run+1030"), Samples.class)).andReturn(response3).once(); GenologicsAPIImpl localApi = context.getBean("genologicsAPI", GenologicsAPIImpl.class); localApi.setRestClient(restMock);// ww w . jav a2 s . com localApi.setServer(new URL("http://lims.cri.camres.org:8080")); EasyMock.replay(restMock); Map<String, Object> terms = new HashMap<String, Object>(); terms.put("projectname", "Run 1030"); List<LimsLink<Sample>> links = localApi.find(terms, Sample.class); EasyMock.verify(restMock); assertEquals("Expected 1150 sample links returned", 1150, links.size()); // Part two - mock the HTTP client and request factory to ensure that the URIs are // being presented as expected without character cludging. HttpContext httpContext = HttpClientContext.create(); HttpClient mockHttpClient = EasyMock.createMock(HttpClient.class); AuthenticatingClientHttpRequestFactory mockRequestFactory = EasyMock .createMock(AuthenticatingClientHttpRequestFactory.class); RestTemplate restTemplate = context.getBean("genologicsRestTemplate", RestTemplate.class); restTemplate.setRequestFactory(mockRequestFactory); localApi.setHttpClient(mockHttpClient); localApi.setRestClient(restTemplate); URI pageOne = new URI("http://lims.cri.camres.org:8080/api/v2/samples?projectname=Run%201030"); URI pageTwo = new URI( "http://lims.cri.camres.org:8080/api/v2/samples?start-index=500&projectname=Run+1030"); URI pageThree = new URI( "http://lims.cri.camres.org:8080/api/v2/samples?start-index=1000&projectname=Run+1030"); HttpGet getOne = new HttpGet(pageOne); HttpGet getTwo = new HttpGet(pageOne); HttpGet getThree = new HttpGet(pageOne); HttpResponse responseOne = createMultipageFetchResponse(pageFiles[0]); HttpResponse responseTwo = createMultipageFetchResponse(pageFiles[1]); HttpResponse responseThree = createMultipageFetchResponse(pageFiles[2]); Class<?> requestClass = Class.forName("org.springframework.http.client.HttpComponentsClientHttpRequest"); Constructor<?> constructor = requestClass.getDeclaredConstructor(HttpClient.class, HttpUriRequest.class, HttpContext.class); constructor.setAccessible(true); ClientHttpRequest reqOne = (ClientHttpRequest) constructor.newInstance(mockHttpClient, getOne, httpContext); ClientHttpRequest reqTwo = (ClientHttpRequest) constructor.newInstance(mockHttpClient, getTwo, httpContext); ClientHttpRequest reqThree = (ClientHttpRequest) constructor.newInstance(mockHttpClient, getThree, httpContext); EasyMock.expect(mockRequestFactory.createRequest(pageOne, HttpMethod.GET)).andReturn(reqOne).once(); EasyMock.expect(mockRequestFactory.createRequest(pageTwo, HttpMethod.GET)).andReturn(reqTwo).once(); EasyMock.expect(mockRequestFactory.createRequest(pageThree, HttpMethod.GET)).andReturn(reqThree).once(); EasyMock.expect(mockHttpClient.execute(getOne, httpContext)).andReturn(responseOne).once(); EasyMock.expect(mockHttpClient.execute(getTwo, httpContext)).andReturn(responseTwo).once(); EasyMock.expect(mockHttpClient.execute(getThree, httpContext)).andReturn(responseThree).once(); EasyMock.replay(mockHttpClient, mockRequestFactory); links = localApi.find(terms, Sample.class); EasyMock.verify(mockHttpClient, mockRequestFactory); assertEquals("Expected 1150 sample links returned", 1150, links.size()); }