List of usage examples for java.lang.reflect Method setAccessible
@Override @CallerSensitive public void setAccessible(boolean flag)
From source file:com.hp.mqm.clt.CliParserTest.java
@Test public void testArgs_inputFiles() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ParseException, URISyntaxException, IOException { CliParser cliParser = new CliParser(); Method inputFilesValidation = cliParser.getClass().getDeclaredMethod("addInputFilesToSettings", CommandLine.class, Settings.class); inputFilesValidation.setAccessible(true); CommandLineParser parser = new DefaultParser(); CommandLine cmdArgs = parser.parse(options, new String[] { "test.xml" }); Settings settings = new Settings(); Boolean result = (Boolean) inputFilesValidation.invoke(cliParser, cmdArgs, settings); Assert.assertFalse(result);/*ww w. j a va 2s .c o m*/ Assert.assertNull(settings.getInputXmlFileNames()); cmdArgs = parser.parse(options, new String[] { getClass().getResource("JUnit-minimalAccepted.xml").toURI().getPath(), getClass().getResource("JUnit-missingTestName.xml").toURI().getPath() }); result = (Boolean) inputFilesValidation.invoke(cliParser, cmdArgs, settings); Assert.assertTrue(result); List<String> fileNames = settings.getInputXmlFileNames(); Assert.assertNotNull(fileNames); Assert.assertEquals(2, fileNames.size()); Assert.assertTrue(fileNames.get(0).contains("JUnit-minimalAccepted.xml")); Assert.assertTrue(fileNames.get(1).contains("JUnit-missingTestName.xml")); }
From source file:io.stallion.plugins.javascript.JavaToJsHelpers.java
public Object inspect(Object object) throws Exception { if (!Settings.instance().getLocalMode()) { Log.error("You can only call 'inspect' in local mode"); return ""; }/*w ww. j a v a2s . c o m*/ Class<?> c = Class.forName("jdk.nashorn.internal.runtime.DebuggerSupport");//full package name //note: getConstructor() can return only public constructors, //you need to use Method method = c.getDeclaredMethod("valueInfos", Object.class, boolean.class); //valueInfos(Object object, boolean all) //Constructor<?> constructor = c.getDeclaredConstructor(); method.setAccessible(true); Object[] objects = (Object[]) method.invoke(null, object, true); //List<Map> returnObjects = new ArrayList<>(); Map desc = new HashMap<>(); for (Object o : objects) { Map map = new HashMap<>(); Field field = o.getClass().getDeclaredField("key"); field.setAccessible(true); Object key = field.get(o); Field field2 = o.getClass().getDeclaredField("valueAsString"); field2.setAccessible(true); Object val = field2.get(o); desc.put(key.toString(), val.toString()); } return desc; }
From source file:org.ovirt.engine.sdk4.internal.HttpConnection.java
@Override public <TYPE> TYPE followLink(TYPE object) { if (!isLink(object)) { throw new Error("Can't follow link because object don't have any"); }//from w ww . j a v a 2s .c om String href = getHref(object); if (href == null) { throw new Error("Can't follow link because the 'href' attribute does't have a value"); } try { URL url = new URL(getUrl()); String prefix = url.getPath(); if (!prefix.endsWith("/")) { prefix += "/"; } if (!href.startsWith(prefix)) { throw new Error("The URL '" + href + "' isn't compatible with the base URL of the connection"); } // Get service based on path String path = href.substring(prefix.length()); Service service = systemService().service(path); // Obtain method which provides result object and invoke it: Method get; if (object instanceof ListWithHref) { get = service.getClass().getMethod("list"); } else { get = service.getClass().getMethod("get"); } Object getRequest = get.invoke(service); Method send = getRequest.getClass().getMethod("send"); send.setAccessible(true); Object getResponse = send.invoke(getRequest); Method obtainObject = getResponse.getClass().getDeclaredMethods()[0]; obtainObject.setAccessible(true); return (TYPE) obtainObject.invoke(getResponse); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) { throw new Error(String.format("Unexpected error while following link \"%1$s\"", href), ex); } catch (MalformedURLException ex) { throw new Error(String.format("Error while creating URL \"%1$s\"", getUrl()), ex); } }
From source file:cn.powerdash.libsystem.common.exception.AbstractExceptionHandler.java
private String getJsonNameFromMethod(final Field errorField, Class<?> dtoClass) { /** find annotation from get/set method........ **/ String methodName = "set" + errorField.getName().substring(0, 1).toUpperCase() + errorField.getName().substring(1); try {//w ww .java 2 s .co m Method method = dtoClass.getDeclaredMethod(methodName, errorField.getType()); method.setAccessible(true); JsonProperty jsonProperty2 = method.getAnnotation(JsonProperty.class); if (jsonProperty2 != null) { String jp = jsonProperty2.value(); LOGGER.debug("JsonProperty from SetMethod ===== " + jp); return jp; } } catch (NoSuchMethodException e) { LOGGER.debug("NoSuchMethodException {}, try to get JsonProperty from super class", methodName); try { /** * Get JsonProperty from super class. It is only a simple implementation base on one assumption that * super class should exist this field. It does not process recursion. * **/ Method method = dtoClass.getSuperclass().getDeclaredMethod(methodName, errorField.getType()); method.setAccessible(true); JsonProperty jsonProperty2 = method.getAnnotation(JsonProperty.class); if (jsonProperty2 != null) { String jp = jsonProperty2.value(); LOGGER.debug("JsonProperty from Super {} `s SetMethod ===== {} ", dtoClass.getSuperclass(), jp); return jp; } } catch (Exception ex) { // NOSONAR LOGGER.debug(e.getMessage()); } } catch (SecurityException e) { LOGGER.debug(e.getMessage()); } return null; }
From source file:com.mousefeed.eclipse.ActionActionDescGenerator.java
/** * Retrieves command handler from a command. * /* w w w. j a va 2 s . c o m*/ * @param command * the command to retrieve the handler from. Not * <code>null</code>. * @return the handler. Returns <code>null</code>, if can't retrieve a * handler. */ private IHandler getCommandHandler(final Command command) { try { final Method method = Command.class.getDeclaredMethod("getHandler"); method.setAccessible(true); return (IHandler) method.invoke(command); } catch (final SecurityException e) { // want to know when this happens throw new RuntimeException(e); } catch (final NoSuchMethodException e) { // should never happen throw new AssertionError(e); } catch (final IllegalAccessException e) { // should never happen throw new AssertionError(e); } catch (final InvocationTargetException e) { // should never happen throw new AssertionError(e); } }
From source file:eu.tripledframework.eventstore.infrastructure.ReflectionObjectConstructor.java
private void applyDomainEvent(T instance, DomainEvent event) { Method method = getEventHandlerMethods(event); if (method == null) { throw new AggregateRootReconstructionException( String.format("Could not find a suitable method for event %s", event)); }//from w w w . j ava2 s . co m try { method.setAccessible(true); Object[] parameters = getParametersValues(method.getParameterAnnotations(), event); method.invoke(instance, parameters); LOGGER.debug("Applied {}", event); } catch (IllegalAccessException | InvocationTargetException e) { throw new AggregateRootReconstructionException( String.format("Could not apply event %s to instance %s", event, instance), e); } }
From source file:com.app.test.mail.DefaultMailSenderTest.java
@Test public void testPopulateEmailMessage() throws Exception { _initializeVelocityTemplate(_clazz, _classInstance); Method populateEmailMessageMethod = _clazz.getDeclaredMethod("_populateEmailMessage", Map.class, String.class, String.class, Session.class); populateEmailMessageMethod.setAccessible(true); List<SearchResult> searchResults = new ArrayList<>(); SearchQuery searchQuery = new SearchQuery(1, _USER_ID, "Test keywords"); SearchResult searchResult = new SearchResult(1, "1234", "itemTitle", "$14.99", "$29.99", "http://www.ebay.com/itm/1234", "http://www.ebay.com/123.jpg"); searchResults.add(searchResult);/* www. j a v a 2 s .co m*/ Map<SearchQuery, List<SearchResult>> searchQueryResultMap = new HashMap<>(); searchQueryResultMap.put(searchQuery, searchResults); Message message = (Message) populateEmailMessageMethod.invoke(_classInstance, searchQueryResultMap, "user@test.com", "unsubscribeToken", _session); Assert.assertEquals("Auction Alert <test@test.com>", message.getFrom()[0].toString()); Assert.assertTrue(message.getSubject().contains("New Search Results - ")); Assert.assertEquals(_EMAIL_CONTENT, message.getContent()); InternetAddress[] internetAddresses = new InternetAddress[1]; internetAddresses[0] = new InternetAddress("user@test.com"); Assert.assertArrayEquals(internetAddresses, message.getRecipients(Message.RecipientType.TO)); }
From source file:com.app.test.util.SearchResultUtilTest.java
@Test public void testDeleteOldResultsWithAllNewResults() throws Exception { Method method = _clazz.getDeclaredMethod("_deleteOldResults", List.class, int.class); method.setAccessible(true); _addSearchResult("1234"); _addSearchResult("2345"); _addSearchResult("3456"); _addSearchResult("4567"); _addSearchResult("5678"); List<SearchResult> searchResults = SearchResultUtil.getSearchQueryResults(_SEARCH_QUERY_ID); method.invoke(_classInstance, searchResults, 5); searchResults = SearchResultUtil.getSearchQueryResults(_SEARCH_QUERY_ID); Assert.assertEquals(0, searchResults.size()); }
From source file:com.app.test.util.SearchResultUtilTest.java
@Test public void testDeleteOldResultsWithNoNewResults() throws Exception { Method method = _clazz.getDeclaredMethod("_deleteOldResults", List.class, int.class); method.setAccessible(true); _addSearchResult("1234"); _addSearchResult("2345"); _addSearchResult("3456"); _addSearchResult("4567"); _addSearchResult("5678"); List<SearchResult> searchResults = SearchResultUtil.getSearchQueryResults(_SEARCH_QUERY_ID); method.invoke(_classInstance, searchResults, 0); searchResults = SearchResultUtil.getSearchQueryResults(_SEARCH_QUERY_ID); Assert.assertEquals(5, searchResults.size()); }
From source file:com.app.test.util.SearchResultUtilTest.java
@Test public void testDeleteOldResultsWithPartialNewResults() throws Exception { Method method = _clazz.getDeclaredMethod("_deleteOldResults", List.class, int.class); method.setAccessible(true); _addSearchResult("1234"); _addSearchResult("2345"); _addSearchResult("3456"); _addSearchResult("4567"); _addSearchResult("5678"); List<SearchResult> searchResults = SearchResultUtil.getSearchQueryResults(_SEARCH_QUERY_ID); method.invoke(_classInstance, searchResults, 3); searchResults = SearchResultUtil.getSearchQueryResults(_SEARCH_QUERY_ID); Assert.assertEquals(2, searchResults.size()); }