下面列出了android.content.pm.PackageStats#java.lang.reflect.Method 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static void checkRes(String resName) throws Exception {
System.out.println("Checking " + resName + "...");
Class clazz = Class.forName(resName);
Method m = clazz.getMethod("getContents");
Object[][] contents = (Object[][])m.invoke(clazz.newInstance());
Set<String> keys = new HashSet<String>();
for (Object[] pair: contents) {
String key = (String)pair[0];
if (keys.contains(key)) {
System.out.println("Found dup: " + key);
throw new Exception();
}
checkKey(key);
keys.add(key);
}
}
private File getClientLib(String discoveryDocString) throws Exception {
Class<?> clientLibGenerator =
loader.loadClass("com.google.api.server.spi.tools.CloudClientLibGenerator");
Method clientLibGeneratorMethod = null;
clientLibGeneratorMethod = clientLibGenerator.getMethod("generateClientLib",
String.class, /* discoveryDoc */
String.class, /* language */
String.class, /* languageVersion */
String.class, /* layout */
File.class /* file */);
File destFile =
File.createTempFile("client_lib", ".zip", tmpFolder.getRoot().getAbsoluteFile());
ArrayList<Object> methodArgs = new ArrayList<Object>();
methodArgs.add(discoveryDocString);
methodArgs.add("JAVA");
methodArgs.add("1.18.0-rc");
methodArgs.add(null);
methodArgs.add(destFile);
Object clientLibGeneratorInstance =
clientLibGenerator.getMethod("using", String.class).invoke(null, CLIENT_LIB_GENERATOR);
clientLibGeneratorMethod.invoke(clientLibGeneratorInstance, methodArgs.toArray());
return destFile;
}
/**
* Processes a method invocation on a proxy instance and returns the
* result.
*
* @param proxy
* the proxy instance that the method was invoked on
* @param method
* the <code>Method</code> instance corresponding to
* the interface method invoked on the proxy instance.
* @param args
* an array of objects containing the values of the
* arguments passed in the method invocation on the proxy
* instance.
* @return the value to return from the method invocation on the
* proxy instance.
* @throws Throwable
* the exception to throw from the method
* invocation on the proxy instance.
* @see InvocationHandler#invoke(Object, Method, Object[])
*/
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
final Class<?> listenerClass = method.getDeclaringClass();
final List<Object> targets = m_listeners.get(listenerClass);
if (LengthUtils.isNotEmpty(targets)) {
final Task task = new Task(targets, method, args);
switch (m_type) {
case AsyncUI:
m_base.runOnUiThread(task);
break;
case SeparatedThread:
new Thread(task).start();
break;
case Direct:
default:
task.run();
break;
}
}
return null;
}
protected void removeEJBObject(final Method callMethod, final Object[] args, final ThreadContext callContext, final InterfaceType type) throws OpenEJBException {
callContext.setCurrentOperation(Operation.REMOVE);
final BeanContext beanContext = callContext.getBeanContext();
final TransactionPolicy txPolicy = createTransactionPolicy(beanContext.getTransactionType(callMethod, type), callContext);
EntityBean bean = null;
try {
bean = instanceManager.obtainInstance(callContext);
ejbLoad_If_No_Transaction(callContext, bean);
bean.ejbRemove();
didRemove(bean, callContext);
instanceManager.poolInstance(callContext, bean, callContext.getPrimaryKey());
} catch (final Throwable e) {
handleException(txPolicy, e, callContext, bean);
} finally {
afterInvoke(txPolicy, callContext);
}
}
/**
* Calls the {@link TmfAbstractAnalysisModule#executeAnalysis} method of an
* analysis module. This method does not return until the analysis is
* completed and it returns the result of the method. It allows to execute
* the analysis without requiring an Eclipse job and waiting for completion.
*
* Note that executing an analysis using this method will not automatically
* execute the dependent analyses module. The execution of those modules is
* left to the caller.
*
* @param module
* The analysis module to execute
* @return The return value of the
* {@link TmfAbstractAnalysisModule#executeAnalysis} method
*/
public static boolean executeAnalysis(IAnalysisModule module) {
if (module instanceof TmfAbstractAnalysisModule) {
try {
Class<?>[] argTypes = new Class[] { IProgressMonitor.class };
Method method = TmfAbstractAnalysisModule.class.getDeclaredMethod("executeAnalysis", argTypes);
method.setAccessible(true);
Boolean result = (Boolean) method.invoke(module, new NullProgressMonitor());
// Set the module as completed, to avoid another call creating a job
method = TmfAbstractAnalysisModule.class.getDeclaredMethod("setAnalysisCompleted", new Class[] { } );
method.setAccessible(true);
method.invoke(module);
return result;
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
fail(e.toString());
}
}
throw new RuntimeException("This analysis module does not have a protected method to execute. Maybe it can be executed differently? Or it is not supported yet in this method?");
}
public void run() {
for (String name : this.names) {
Object bean;
try {
bean = this.loader.loadClass(name).newInstance();
} catch (Exception exception) {
throw new Error("could not instantiate bean: " + name, exception);
}
if (this.loader != bean.getClass().getClassLoader()) {
throw new Error("bean class loader is not equal to default one");
}
PropertyDescriptor[] pds = getPropertyDescriptors(bean);
for (PropertyDescriptor pd : pds) {
Class type = pd.getPropertyType();
Method setter = pd.getWriteMethod();
Method getter = pd.getReadMethod();
if (type.equals(String.class)) {
executeMethod(setter, bean, "Foo");
} else if (type.equals(int.class)) {
executeMethod(setter, bean, Integer.valueOf(1));
}
executeMethod(getter, bean);
}
}
}
/**
* 检查方法是否包含一个参数,为StreamObserver
*
* @param methodCallProperty 方法
*/
private void checkOneParamHasStreamObServer(MethodCallProperty methodCallProperty) {
Method method = methodCallProperty.getMethod();
//判断当前方法是否仅包含一个参数,为StreamObserver。如果不是,抛出异常。
Type[] types = method.getGenericParameterTypes();
if (types == null || types.length != 1) {
throw new GRpcMethodNoMatchException(method.getDeclaringClass().getName(), method.getName(), methodCallProperty.getMethodType().name(),
"You should use one param [StreamObserver] in your method.Please check it.");
}
//检查第一个参数是否为StreamObserver
Type type = Utils.safeElement(types, 0);
if (type instanceof ParameterizedType) {
if (!((ParameterizedType) type).getRawType().getTypeName().equals(StreamObserver.class.getName())) {
throw new GRpcMethodNoMatchException(method.getDeclaringClass().getName(), method.getName(), methodCallProperty.getMethodType().name(),
"You should use one param [StreamObserver] in your method.Please check it.");
}
} else {
if (!type.getTypeName().equals(StreamObserver.class.getName())) {
throw new GRpcMethodNoMatchException(method.getDeclaringClass().getName(), method.getName(), methodCallProperty.getMethodType().name(),
"You should use one param [StreamObserver] in your method.Please check it.");
}
}
}
@Test
public void testGetPropertySetterMethod() throws Exception {
Method method = TestReflect.class.getMethod("setS", int.class);
Assert.assertEquals(method, getPropertySetterMethod(TestReflect.class, "s", int.class));
method = TestReflect.class.getMethod("setB", boolean.class);
Assert.assertEquals(method, getPropertySetterMethod(TestReflect.class, "b", boolean.class));
boolean error = false;
try {
getPropertySetterMethod(TestReflect.class, "xxx", String.class);
} catch (Exception e) {
error = true;
}
Assert.assertTrue(error);
}
@RuntimeType
public static List getVertexes(@This final VertexFrame thiz, @Origin final Method method, @RuntimeType @Argument(0) final Class type) {
assert thiz instanceof CachesReflection;
final Adjacency annotation = ((CachesReflection) thiz).getReflectionCache().getAnnotation(method, Adjacency.class);
final Direction direction = annotation.direction();
final String label = annotation.label();
final TypeResolver resolver = thiz.getGraph().getTypeResolver();
return thiz.traverse(input -> {
switch(direction) {
case IN:
return resolver.hasType(input.in(label), type);
case OUT:
return resolver.hasType(input.out(label), type);
case BOTH:
return resolver.hasType(input.both(label), type);
default:
throw new IllegalStateException("Direction not recognized.");
}
}).toList(type);
}
public static JsonObject getResourceMethodIndexNode(String pathPrefix, Collection<Method> methods, ArgsUriPart args, boolean addPsfQueryParams) throws Exception {
JsonObject indexNode = new JsonObject();
if (methods != null) {
Iterator<Method> it = methods.iterator();
while (it.hasNext()) {
Method field = it.next();
JsonObject methodNode = new JsonObject();
String resource = joinUri(pathPrefix, args.getMethodTransfilter().transform(field.getName()));
Set<NamedParameter> queryParams = args.getNamedParameters(field.getName(), true);
if (addPsfQueryParams) {
queryParams.addAll(PSFUriPart.SLURPED_NAMED_QUERY_PARAMETERS);
}
methodNode.add(JS_QUERY_PARAMS_FIELD, createQueryParameterNode(queryParams));
methodNode.add(JS_OUT_VO_FIELD, createVOReturnTypeNode(field.getReturnType(), field.getGenericReturnType()));
indexNode.add(resource, methodNode);
}
}
return indexNode;
}
@Test
public void testMatches4() throws Exception {
Method m1 = I4.class.getMethod("foo");
Method m2 = C4.class.getMethod("foo");
Assert.assertTrue(pc.matches(m1, C4.class));
Assert.assertTrue(pc.matches(m2, C4.class));
Assert.assertTrue(pc.matches(m1, I4.class));
Assert.assertTrue(pc.matches(m2, I4.class));
Assert.assertFalse(map.getByMethodInfo(CachePointcut.getKey(m1, I4.class)).isEnableCacheContext());
Assert.assertNotNull(map.getByMethodInfo(CachePointcut.getKey(m1, I4.class)).getCachedAnnoConfig());
Assert.assertTrue(map.getByMethodInfo(CachePointcut.getKey(m1, C4.class)).isEnableCacheContext());
Assert.assertNotNull(map.getByMethodInfo(CachePointcut.getKey(m1, C4.class)).getCachedAnnoConfig());
Assert.assertTrue(map.getByMethodInfo(CachePointcut.getKey(m2, I4.class)).isEnableCacheContext());
Assert.assertNotNull(map.getByMethodInfo(CachePointcut.getKey(m2, I4.class)).getCachedAnnoConfig());
Assert.assertTrue(map.getByMethodInfo(CachePointcut.getKey(m2, C4.class)).isEnableCacheContext());
Assert.assertNotNull(map.getByMethodInfo(CachePointcut.getKey(m2, C4.class)).getCachedAnnoConfig());
}
private Method getMethod(String name, Class<?>[] parameterTypes, boolean recursivePublicMethods)
throws NoSuchMethodException {
if (name == null) {
throw new NullPointerException("name == null");
}
if (parameterTypes == null) {
parameterTypes = EmptyArray.CLASS;
}
for (Class<?> c : parameterTypes) {
if (c == null) {
throw new NoSuchMethodException("parameter type is null");
}
}
Method result = recursivePublicMethods ? getPublicMethodRecursive(name, parameterTypes)
: getDeclaredMethodInternal(name, parameterTypes);
// Fail if we didn't find the method or it was expected to be public.
if (result == null ||
(recursivePublicMethods && !Modifier.isPublic(result.getAccessFlags()))) {
throw new NoSuchMethodException(name + " " + Arrays.toString(parameterTypes));
}
return result;
}
/** Read resolve to the read object.
* We give chance to actual instance to do its own resolution as well. It
* is necessary for achieving back compatability of certain types of settings etc.
*/
private Object readResolve() throws ObjectStreamException {
SharedClassObject resolved = object;
Method resolveMethod = findReadResolveMethod(object.getClass());
if (resolveMethod != null) {
// invoke resolve method and accept its result
try {
// make readResolve accessible (it can have any access modifier)
resolveMethod.setAccessible(true);
return resolveMethod.invoke(object);
} catch (Exception ex) {
// checked or runtime does not matter - we must survive
String banner = "Skipping " + object.getClass() + " resolution:"; //NOI18N
err.log(Level.WARNING, banner, ex);
} finally {
resolveMethod.setAccessible(false);
}
}
return resolved;
}
private static Method tryFindClientMethod(Object client, String name) {
// TODO: Cache me.
for (Method method : client.getClass().getMethods()) {
if (!method.getName().equals(name)) {
continue;
}
Class<?>[] parameters = method.getParameterTypes();
if (parameters.length != 1) {
continue;
}
// This is the inverse of the normal approach of findMethod() -
// we're looking for a method which will accept a specific subtype
// of AmazonWebServiceRequest, without worrying overmuch about
// what subtype it is. We'll create an object of the appropriate
// type and fill it in.
if (AmazonWebServiceRequest.class.isAssignableFrom(parameters[0])) {
return method;
}
}
return null;
}
/**
* 引数に存在しないファイルパスを渡した場合_レスポンスボディに空文字列が入ったSC_OKレスポンスが返る.
*/
@Test
public void 引数に存在しないファイルパスを渡した場合_レスポンスボディに空文字列が入ったSC_OKレスポンスが返る() {
TestLogResource logResource = new TestLogResource();
try {
Method method = LogResource.class.getDeclaredMethod("getLog", new Class[] {String.class, String.class });
method.setAccessible(true);
String filename = "/non-existing-file-path";
Object result = method.invoke(logResource, new Object[] {"current", filename });
assertNotNull(result);
assertTrue(result instanceof Response);
assertEquals(HttpStatus.SC_OK, ((Response) result).getStatus());
assertTrue(((Response) result).getEntity() instanceof String);
assertEquals(0, ((String) ((Response) result).getEntity()).length());
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
protected Double getProperty(Object bean, String name) {
try {
// Get the value of prop
String prop = "get" + name.substring(0,1).toUpperCase() + name.substring(1);
Method meth = bean.getClass().getMethod(prop, new Class[0]);
Object property = meth.invoke(bean, new Object[0]);
if (meth.getReturnType().equals(Double.TYPE)) {
return (Double) property;
} else if (meth.getReturnType().equals(Long.TYPE)) {
return Double.valueOf(((Long) property).doubleValue());
} else {
fail("wrong type: " + meth.getReturnType().getName());
}
} catch (NoSuchMethodException nsme) {
// ignored
} catch (InvocationTargetException ite) {
fail(ite.getMessage());
} catch (IllegalAccessException iae) {
fail(iae.getMessage());
}
return null;
}
/**
* Creates an <TT>EventSetDescriptor</TT> assuming that you are
* following the most simple standard design pattern where a named
* event "fred" is (1) delivered as a call on the single method of
* interface FredListener, (2) has a single argument of type FredEvent,
* and (3) where the FredListener may be registered with a call on an
* addFredListener method of the source component and removed with a
* call on a removeFredListener method.
*
* @param sourceClass The class firing the event.
* @param eventSetName The programmatic name of the event. E.g. "fred".
* Note that this should normally start with a lower-case character.
* @param listenerType The target interface that events
* will get delivered to.
* @param listenerMethodName The method that will get called when the event gets
* delivered to its target listener interface.
* @exception IntrospectionException if an exception occurs during
* introspection.
*/
public EventSetDescriptor(Class<?> sourceClass, String eventSetName,
Class<?> listenerType, String listenerMethodName)
throws IntrospectionException {
this(sourceClass, eventSetName, listenerType,
new String[] { listenerMethodName },
Introspector.ADD_PREFIX + getListenerClassName(listenerType),
Introspector.REMOVE_PREFIX + getListenerClassName(listenerType),
Introspector.GET_PREFIX + getListenerClassName(listenerType) + "s");
String eventName = NameGenerator.capitalize(eventSetName) + "Event";
Method[] listenerMethods = getListenerMethods();
if (listenerMethods.length > 0) {
Class[] args = getParameterTypes(getClass0(), listenerMethods[0]);
// Check for EventSet compliance. Special case for vetoableChange. See 4529996
if (!"vetoableChange".equals(eventSetName) && !args[0].getName().endsWith(eventName)) {
throw new IntrospectionException("Method \"" + listenerMethodName +
"\" should have argument \"" +
eventName + "\"");
}
}
}
protected ACC accumulateValues(List<T> values)
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
AggregateFunction<T, ACC> aggregator = getAggregator();
ACC accumulator = getAggregator().createAccumulator();
Method accumulateFunc = getAccumulateFunc();
for (T value : values) {
if (accumulateFunc.getParameterCount() == 1) {
accumulateFunc.invoke(aggregator, (Object) accumulator);
} else if (accumulateFunc.getParameterCount() == 2) {
accumulateFunc.invoke(aggregator, (Object) accumulator, (Object) value);
} else {
throw new TableException("Unsupported now");
}
}
return accumulator;
}
@Test
public void allMethodsForwarded() throws Exception {
ForwardingTestUtil.testMethodsForwarded(
ManagedChannelBuilder.class,
mockDelegate,
testChannelBuilder,
Collections.<Method>emptyList(),
new ForwardingTestUtil.ArgumentProvider() {
@Override
public Object get(Method method, int argPos, Class<?> clazz) {
if (method.getName().equals("maxInboundMetadataSize")) {
assertThat(argPos).isEqualTo(0);
return 1; // an arbitrary positive number
}
return null;
}
});
}
@Test
public void illegalArgumentException() {
this.resolvers.add(stubResolver(1));
Method method = ResolvableMethod.on(TestController.class).mockCall(o -> o.singleArg(null)).method();
Mono<HandlerResult> mono = invoke(new TestController(), method);
try {
mono.block();
fail("Expected IllegalStateException");
}
catch (IllegalStateException ex) {
assertNotNull("Exception not wrapped", ex.getCause());
assertTrue(ex.getCause() instanceof IllegalArgumentException);
assertTrue(ex.getMessage().contains("Controller ["));
assertTrue(ex.getMessage().contains("Method ["));
assertTrue(ex.getMessage().contains("with argument values:"));
assertTrue(ex.getMessage().contains("[0] [type=java.lang.Integer] [value=1]"));
}
}
@Test public void When_Call_OnIllegalMock_Response_With_Custom_Response_Adapter_Adapt_It()
throws NoSuchMethodException, IOException {
Method method = Providers.class.getDeclaredMethod("singleResponseMock");
Rx2Retrofit annotation =
PlaceholderRetrofitErrorResponseAdapterAnnotation.class.getAnnotation(Rx2Retrofit.class);
Metadata<Rx2Retrofit> metadata = new Metadata(Providers.class,
method, null, annotation, method.getGenericReturnType());
Single single =
(Single) rx2RetrofitInterceptor.onIllegalMock(new AssertionError("BOOM!"), metadata);
TestObserver<Response<Mock>> subscriber = single.test();
subscriber.awaitTerminalEvent();
subscriber.assertNoErrors();
subscriber.assertValueCount(1);
Response<Mock> response = subscriber.values().get(0);
assertNull(response.body());
assertThat(response.errorBody().string(), is("{'message':'BOOM!'}"));
}
private static Method findMethod(Object instance, String name, Class<?>... parameterTypes)
throws NoSuchMethodException {
for (Class<?> clazz = instance.getClass(); clazz != null; clazz = clazz.getSuperclass()) {
try {
Method method = clazz.getDeclaredMethod(name, parameterTypes);
if (!method.isAccessible()) {
method.setAccessible(true);
}
return method;
} catch (NoSuchMethodException e) {
// ignore and search next
}
}
throw new NoSuchMethodException("Method " + name + " with parameters " +
Arrays.asList(parameterTypes) + " not found in " + instance.getClass());
}
@Test public void When_Call_Adapt_Type_With_Observable_Response_List_Mock_Then_Unwrap_Its_Value() throws NoSuchMethodException {
Method method = Providers.class.getDeclaredMethod("observableResponseMocks");
RxRetrofit annotation = PlaceholderRetrofitAnnotation.class.getAnnotation(RxRetrofit.class);
Metadata<RxRetrofit> metadata = new Metadata(Providers.class,
method, null, annotation, method.getGenericReturnType());
Type methodType = method.getGenericReturnType();
Type expectedType = Types.newParameterizedType(List.class, Mock.class);
Type adaptedType = rxRetrofitInterceptor
.adaptType(methodType, metadata);
assertEquals(expectedType, adaptedType);
}
protected void newWindow(LoggingPreferences lp) {
try
{
Method m = getClass().getMethod("setupDriver"+getSession().browserName, new Class[]{LoggingPreferences.class});
if(m!=null) {
m.invoke(this, new Object[]{lp});
}
getSession().__wpos__++;
}
catch (Exception e)
{
throw new RuntimeException("Invalid browser name specified");
}
}
public void testMultiNodeMethodsArg0() throws Exception
{
runAs("andy");
Object o = new ClassWithMethods();
Method method = o.getClass().getMethod("testManyNodeRef",
new Class[] { NodeRef.class, NodeRef.class, NodeRef.class, NodeRef.class });
AdvisorAdapterRegistry advisorAdapterRegistry = GlobalAdvisorAdapterRegistry.getInstance();
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.addAdvisor(advisorAdapterRegistry.wrap(new Interceptor("ACL_NODE.0.sys:base.Read")));
proxyFactory.setTargetSource(new SingletonTargetSource(o));
Object proxy = proxyFactory.getProxy();
method.invoke(proxy, new Object[] { null, null, null, null });
try
{
method.invoke(proxy, new Object[] { rootNodeRef, null, null, null });
assertNotNull(null);
}
catch (InvocationTargetException e)
{
}
permissionService.setPermission(new SimplePermissionEntry(rootNodeRef, getPermission(PermissionService.READ),
"andy", AccessStatus.ALLOWED));
method.invoke(proxy, new Object[] { rootNodeRef, null, null, null });
}
public boolean matchesMethod(Class<?> clazz, Method method, ScanResult scanResult) {
if (clazz.getName().equals(className)
&& method.getName().equals(methodName)
&& method.getParameterCount() == parameterTypeSignature.length)
{
boolean paramsMatch = true;
for (int i = 0; i < parameterTypeSignature.length; i++) {
paramsMatch = paramsMatch && parameterTypeSignature[i].instantiate(scanResult) == method.getParameters()[i].getType();
}
return paramsMatch;
}
return false;
}
private static Map<String, DefaultValueHolder> computeDefaultValues(
Class<? extends Annotation> annotationType) {
AttributeMethods methods = AttributeMethods.forAnnotationType(annotationType);
if (!methods.hasDefaultValueMethod()) {
return Collections.emptyMap();
}
Map<String, DefaultValueHolder> result = new LinkedHashMap<>(methods.size());
if (!methods.hasNestedAnnotation()) {
// Use simpler method if there are no nested annotations
for (int i = 0; i < methods.size(); i++) {
Method method = methods.get(i);
Object defaultValue = method.getDefaultValue();
if (defaultValue != null) {
result.put(method.getName(), new DefaultValueHolder(defaultValue));
}
}
}
else {
// If we have nested annotations, we need them as nested maps
AnnotationAttributes attributes = MergedAnnotation.of(annotationType)
.asMap(annotation ->
new AnnotationAttributes(annotation.getType(), true), Adapt.ANNOTATION_TO_MAP);
for (Map.Entry<String, Object> element : attributes.entrySet()) {
result.put(element.getKey(), new DefaultValueHolder(element.getValue()));
}
}
return result;
}
/**
* Registers post condition checks to a method's return value
*
* @throws IllegalArgumentException if <code>method == null</code> or <code>checks == null</code> or checks is empty
* @throws InvalidConfigurationException if the declaring class is not guarded
*/
public void removeChecks(final Method method, final PostCheck... checks) throws InvalidConfigurationException {
Assert.argumentNotNull("method", method);
Assert.argumentNotEmpty("checks", checks);
getClassChecks(method.getDeclaringClass()).removeMethodPostChecks(method, checks);
}
private AudioInputStream invokeOpenStream(Synthesizer synthesizer, AudioFormat audioFormat, Map<String, Object> map) throws Throwable {
Class<?>[] methodSignature = new Class[]{AudioFormat.class,Map.class};
Object[] methodArguments = new Object[]{audioFormat, map};
Class<?> classInstance = synthesizer.getClass();
Method method = classInstance.getMethod(SYNTHESIZER_OPEN_STREAM_METHOD, methodSignature);
Object returnValue = method.invoke(synthesizer, methodArguments);
return (AudioInputStream)returnValue;
}
public void click() {
// cheat to invoke sendSelectionEvent(), which is private
Class<?>toolItemClass = getClass().getSuperclass().getSuperclass().getSuperclass(); // i.e., Widget class
Method method;
try {
method = toolItemClass.getDeclaredMethod("sendSelectionEvent", int.class, Event.class, boolean.class);
method.setAccessible(true);
method.invoke(this, SWT.Selection, new Event(), false);
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
}