Example usage for java.lang Class getDeclaredMethod

List of usage examples for java.lang Class getDeclaredMethod

Introduction

In this page you can find the example usage for java.lang Class getDeclaredMethod.

Prototype

@CallerSensitive
public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
        throws NoSuchMethodException, SecurityException 

Source Link

Document

Returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.

Usage

From source file:org.opendaylight.nemo.renderer.openflow.physicalnetwork.PhyConfigLoaderTest.java

@Test
public void testBuildHosts() throws Exception {
    Class<PhyConfigLoader> class1 = PhyConfigLoader.class;
    Method method = class1.getDeclaredMethod("buildHosts", new Class[] { JsonNode.class });
    method.setAccessible(true);/*from   w w w.ja va2s . c o  m*/

    JsonNode hostsNode = mock(JsonNode.class);
    JsonNode hosts = mock(JsonNode.class);
    JsonNode host = mock(JsonNode.class);
    JsonNode host_temp = mock(JsonNode.class);
    JsonNode host_temp1 = mock(JsonNode.class);
    JsonNode ipaddrs = mock(JsonNode.class);
    JsonNode ipaddr = mock(JsonNode.class);
    List<PhysicalHost> list;

    when(hostsNode.path(any(String.class))).thenReturn(hosts);
    when(hosts.size()).thenReturn(1);
    when(hosts.get(any(Integer.class))).thenReturn(host);
    //get into method "buildhost"
    when(host.get(any(String.class))).thenReturn(host_temp);
    when(host_temp.asText()).thenReturn(new String("00001111-0000-0000-0000-000011112222")) //HOST_ID
            .thenReturn(new String("hostName")) //HOST_NAME
            .thenReturn(new String("00:11:22:33:44:55")) //MAC_ADDRESS
            .thenReturn(new String("nodeId")) //NODE_ID
            .thenReturn(new String("connetionId"));//PhysicalPortId
    when(host.path(any(String.class))).thenReturn(ipaddrs);
    when(ipaddrs.size()).thenReturn(1);
    when(ipaddrs.get(any(Integer.class))).thenReturn(ipaddr);
    when(ipaddr.get(any(String.class))).thenReturn(host_temp1);
    when(host_temp1.asText()).thenReturn(new String("192.168.1.1"));//ipv4_address

    list = (List<PhysicalHost>) method.invoke(phyConfigLoader, hostsNode);
    Assert.assertTrue(list.size() == 1);
}

From source file:core.AbstractStateMachine.java

/**
 * Invoke the no argument method with the following name.
 *
 * @param methodName The method to invoke.
 * @return Whether the invoke was successful.
 *///from ww  w . ja  v a2  s  .  co  m
public boolean invoke(final String methodName) {
    Class clas = this.getClass();
    try {
        Method method = clas.getDeclaredMethod(methodName, SIGNATURE);
        method.invoke(this, PARAMETERS);
    } catch (SecurityException se) {
        logError(se);
        return false;
    } catch (NoSuchMethodException nsme) {
        logError(nsme);
        return false;
    } catch (IllegalArgumentException iae) {
        logError(iae);
        return false;
    } catch (IllegalAccessException iae) {
        logError(iae);
        return false;
    } catch (InvocationTargetException ite) {
        logError(ite);
        return false;
    }
    return true;
}

From source file:com.kogitune.launcher3.LauncherAppWidgetHostView.java

@Override
public void updateAppWidget(RemoteViews remoteViews) {
    if (EXPERIMENTAL) {
        if (remoteViews != null) {
            Handler mH = null;//  w ww.  j  a va  2 s .c o m
            Field queueField = null;
            MessageQueue messageQueue = null;
            try {
                Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
                Class[] params = new Class[0];
                Method currentActivityThread = activityThreadClass.getDeclaredMethod("currentActivityThread",
                        params);
                Boolean accessible = currentActivityThread.isAccessible();
                currentActivityThread.setAccessible(true);
                Object obj = currentActivityThread.invoke(activityThreadClass);
                if (obj == null) {
                    Log.d("ERROR", "The current activity thread is null!");
                }
                currentActivityThread.setAccessible(accessible);

                Field mHField = activityThreadClass.getDeclaredField("mH");
                mHField.setAccessible(true);
                mH = (Handler) mHField.get(obj);
                queueField = Handler.class.getDeclaredField("mQueue");
                queueField.setAccessible(true);
                messageQueue = (MessageQueue) queueField.get(mH);

                HandlerThread handlerThread = new HandlerThread("other");
                handlerThread.start();
                handlerThread.quit();
                queueField.set(mH, null);

            } catch (Exception e) {
                Log.d("ERROR", Log.getStackTraceString(e));
            }
            Context context = getContext().getApplicationContext();
            NotificationManager notificationManager = (NotificationManager) context.getApplicationContext()
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
            builder.setContent(remoteViews).setSmallIcon(R.drawable.ic_launcher_info_normal_holo)
                    .setContentTitle("My notification") // ?
                    .setContentText("Hello Notification!!"); // ?

            Notification notification = builder.build();
            notificationManager.notify(getAppWidgetId(), notification);

            final Field finalQueueField = queueField;
            final Handler finalMH = mH;
            final MessageQueue finalMessageQueue = messageQueue;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(50L);
                        if (finalMessageQueue != null)
                            finalQueueField.set(finalMH, finalMessageQueue);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();

        }
    }
    // Store the orientation in which the widget was inflated
    mPreviousOrientation = mContext.getResources().getConfiguration().orientation;
    super.updateAppWidget(remoteViews);
}

From source file:org.acegisecurity.intercept.method.MethodDefinitionMap.java

protected ConfigAttributeDefinition lookupAttributes(Method method) {
    ConfigAttributeDefinition definition = new ConfigAttributeDefinition();

    // Add attributes explictly defined for this method invocation
    ConfigAttributeDefinition directlyAssigned = (ConfigAttributeDefinition) this.methodMap.get(method);
    merge(definition, directlyAssigned);

    // Add attributes explicitly defined for this method invocation's interfaces
    Class[] interfaces = method.getDeclaringClass().getInterfaces();

    for (int i = 0; i < interfaces.length; i++) {
        Class clazz = interfaces[i];

        try {// w w  w.  ja  va 2s . com
            // Look for the method on the current interface
            Method interfaceMethod = clazz.getDeclaredMethod(method.getName(),
                    (Class[]) method.getParameterTypes());
            ConfigAttributeDefinition interfaceAssigned = (ConfigAttributeDefinition) this.methodMap
                    .get(interfaceMethod);
            merge(definition, interfaceAssigned);
        } catch (Exception e) {
            // skip this interface
        }
    }

    // Return null if empty, as per abstract superclass contract
    if (definition.size() == 0) {
        return null;
    } else {
        return definition;
    }
}

From source file:org.androidtransfuse.analysis.ActivityAnalysis.java

private ASTMethod getASTMethod(Class type, String methodName, Class... args) {
    try {/* www. j a v a  2 s .  c  o  m*/
        return astClassFactory.getMethod(type.getDeclaredMethod(methodName, args));
    } catch (NoSuchMethodException e) {
        throw new TransfuseAnalysisException(
                "NoSuchMethodException while trying to reference method " + methodName, e);
    }
}

From source file:org.opendaylight.nemo.renderer.openflow.physicalnetwork.PhyConfigLoaderTest.java

@Test
public void testBuildNodes() throws Exception {
    Class<PhyConfigLoader> class1 = PhyConfigLoader.class;
    Method method = class1.getDeclaredMethod("buildNodes", new Class[] { JsonNode.class });
    method.setAccessible(true);//from w  ww  .  j av a 2 s. co m

    JsonNode nodesRoot = mock(JsonNode.class);
    JsonNode nodes = mock(JsonNode.class);
    JsonNode node = mock(JsonNode.class);
    JsonNode node_temp = mock(JsonNode.class);
    JsonNode port_temp = mock(JsonNode.class);
    JsonNode attribute_temp = mock(JsonNode.class);
    JsonNode attribute_temp_son = mock(JsonNode.class);
    JsonNode ports = mock(JsonNode.class);
    JsonNode attributes = mock(JsonNode.class);
    JsonNode portAttributes = mock(JsonNode.class);
    JsonNode portAttribute = mock(JsonNode.class);
    JsonNode attributes_son = mock(JsonNode.class);
    JsonNode port = mock(JsonNode.class);
    List<PhysicalNode> result;

    when(nodesRoot.path(any(String.class))).thenReturn(nodes);
    when(nodes.size()).thenReturn(1);
    when(nodes.get(any(Integer.class))).thenReturn(node);
    //get into method "buildnode"
    when(node.get(any(String.class))).thenReturn(node_temp);
    when(node_temp.asText()).thenReturn(new String(""))//branch null
            .thenReturn(new String("test")) //node_id
            .thenReturn(new String("switch")); //NODE_TYPE

    result = (List<PhysicalNode>) method.invoke(phyConfigLoader, nodesRoot); //return empty list
    Assert.assertTrue(result.size() == 0);
    verify(node_temp).asText();

    when(node.path(any(String.class))).thenReturn(ports)//PORTS
            .thenReturn(attributes);//ATTRIBUTES
    ////get into method "buildports"
    when(ports.size()).thenReturn(1);
    when(ports.get(any(Integer.class))).thenReturn(port);
    ///////get into method "buildport"
    when(port.get(any(String.class))).thenReturn(port_temp);
    when(port_temp.asText()).thenReturn(new String("test"))//PORT_ID
            .thenReturn(new String("switch"));//PORT_TYPE
    when(port.path(any(String.class))).thenReturn(portAttributes);
    ////////get into method "buildportattributes"
    when(portAttributes.size()).thenReturn(1);
    when(portAttributes.get(any(Integer.class))).thenReturn(attributes_son);
    //////////get into method "buildPortAttribute"
    when(attributes_son.path(any(String.class))).thenReturn(attribute_temp_son);
    when(attribute_temp_son.asText()).thenReturn(new String("zm")).thenReturn(new String("zm"));
    ////return to method "buildnode" and get into method "..............buildNodeAttributes"
    when(attributes.size()).thenReturn(1);
    when(attributes.get(any(Integer.class))).thenReturn(portAttribute);
    //////get into method "..............buildNodeAttribute"
    when(portAttribute.path(any(String.class))).thenReturn(attribute_temp);
    when(attribute_temp.asText()).thenReturn(new String("test"))//ATTRIBUTE_NAME
            .thenReturn(new String("test"));//ATTRIBUTE_VALUE

    result = (List<PhysicalNode>) method.invoke(phyConfigLoader, nodesRoot); //return empty list
    Assert.assertTrue(result.size() == 1);

}

From source file:moe.encode.airblock.commands.core.components.ComponentBag.java

/**
 * Returns the correct method for the implementation.
 *
 * @param cls     The class which method should be searched.
 * @param method  The method that should be found.
 * @param handle  The handle that is affected by the holder.
 * @return The method or {@code null} if the method was not found.
 */// www. j  a  v  a 2s.  c  o m
@SuppressWarnings("unchecked")
Method getMethod(Class<?> cls, Method method, Handle<?> handle) {
    Class<?> current = cls;
    while (current.getAnnotation(Components.class) != null) {
        Class<?> handleCls = handle.getClass();
        while (Handle.class.isAssignableFrom(handleCls)) {
            try {
                return current.getDeclaredMethod(method.getName(),
                        ArrayUtils.add(method.getParameterTypes(), 0, handleCls));
            } catch (NoSuchMethodException ignored) {
                handleCls = handleCls.getSuperclass();
            }
        }
        current = current.getSuperclass();
    }
    return null;
}

From source file:net.nym.devicepolicy.MainActivity.java

private Method reflectMethod(Class clazz, String methodName, Class... params) throws NoSuchMethodException {
    return clazz.getDeclaredMethod(methodName, params);
}

From source file:org.neo4j.ogm.auth.AuthenticationTest.java

private boolean isRunningWithNeo4j2Dot2OrLater() throws Exception {
    Class<?> versionClass = null;
    BigDecimal version = new BigDecimal(2.1);
    try {/*from w w w. j  a va2 s. co  m*/
        versionClass = Class.forName("org.neo4j.kernel.Version");
        Method kernelVersion23x = versionClass.getDeclaredMethod("getKernelVersion", null);
        version = new BigDecimal(((String) kernelVersion23x.invoke(null)).substring(0, 3));
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        try {
            Method kernelVersion22x = versionClass.getDeclaredMethod("getKernelRevision", null);
            version = new BigDecimal(((String) kernelVersion22x.invoke(null)).substring(0, 3));
        } catch (NoSuchMethodException e1) {
            throw new RuntimeException("Unable to find a method to get Neo4js kernel version");
        }

    }
    return version.compareTo(new BigDecimal("2.1")) > 0;
}

From source file:Browser.java

/**
 * Called by a static initializer to load any classes, fields, and methods 
 * required at runtime to locate the user's web browser.
 * @return <code>true</code> if all intialization succeeded
 *         <code>false</code> if any portion of the initialization failed
 *///from ww  w .  jav  a2s .  com
private static boolean loadClasses() {
    switch (jvm) {
    case MRJ_2_0:
        try {
            Class aeTargetClass = Class.forName("com.apple.MacOS.AETarget");
            Class osUtilsClass = Class.forName("com.apple.MacOS.OSUtils");
            Class appleEventClass = Class.forName("com.apple.MacOS.AppleEvent");
            Class aeClass = Class.forName("com.apple.MacOS.ae");
            aeDescClass = Class.forName("com.apple.MacOS.AEDesc");

            aeTargetConstructor = aeTargetClass.getDeclaredConstructor(new Class[] { int.class });
            appleEventConstructor = appleEventClass.getDeclaredConstructor(
                    new Class[] { int.class, int.class, aeTargetClass, int.class, int.class });
            aeDescConstructor = aeDescClass.getDeclaredConstructor(new Class[] { String.class });

            makeOSType = osUtilsClass.getDeclaredMethod("makeOSType", new Class[] { String.class });
            putParameter = appleEventClass.getDeclaredMethod("putParameter",
                    new Class[] { int.class, aeDescClass });
            sendNoReply = appleEventClass.getDeclaredMethod("sendNoReply", new Class[] {});

            Field keyDirectObjectField = aeClass.getDeclaredField("keyDirectObject");
            keyDirectObject = (Integer) keyDirectObjectField.get(null);
            Field autoGenerateReturnIDField = appleEventClass.getDeclaredField("kAutoGenerateReturnID");
            kAutoGenerateReturnID = (Integer) autoGenerateReturnIDField.get(null);
            Field anyTransactionIDField = appleEventClass.getDeclaredField("kAnyTransactionID");
            kAnyTransactionID = (Integer) anyTransactionIDField.get(null);
        } catch (ClassNotFoundException cnfe) {
            errorMessage = cnfe.getMessage();
            return false;
        } catch (NoSuchMethodException nsme) {
            errorMessage = nsme.getMessage();
            return false;
        } catch (NoSuchFieldException nsfe) {
            errorMessage = nsfe.getMessage();
            return false;
        } catch (IllegalAccessException iae) {
            errorMessage = iae.getMessage();
            return false;
        }
        break;

    case MRJ_2_1:
        try {
            mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
            mrjOSTypeClass = Class.forName("com.apple.mrj.MRJOSType");
            Field systemFolderField = mrjFileUtilsClass.getDeclaredField("kSystemFolderType");
            kSystemFolderType = systemFolderField.get(null);
            findFolder = mrjFileUtilsClass.getDeclaredMethod("findFolder", new Class[] { mrjOSTypeClass });
            getFileCreator = mrjFileUtilsClass.getDeclaredMethod("getFileCreator", new Class[] { File.class });
            getFileType = mrjFileUtilsClass.getDeclaredMethod("getFileType", new Class[] { File.class });
        } catch (ClassNotFoundException cnfe) {
            errorMessage = cnfe.getMessage();
            return false;
        } catch (NoSuchFieldException nsfe) {
            errorMessage = nsfe.getMessage();
            return false;
        } catch (NoSuchMethodException nsme) {
            errorMessage = nsme.getMessage();
            return false;
        } catch (SecurityException se) {
            errorMessage = se.getMessage();
            return false;
        } catch (IllegalAccessException iae) {
            errorMessage = iae.getMessage();
            return false;
        }
        break;

    case MRJ_3_0:
        try {
            Class linker = Class.forName("com.apple.mrj.jdirect.Linker");
            Constructor constructor = linker.getConstructor(new Class[] { Class.class });
            linkage = constructor.newInstance(new Object[] { Browser.class });
        } catch (ClassNotFoundException cnfe) {
            errorMessage = cnfe.getMessage();
            return false;
        } catch (NoSuchMethodException nsme) {
            errorMessage = nsme.getMessage();
            return false;
        } catch (InvocationTargetException ite) {
            errorMessage = ite.getMessage();
            return false;
        } catch (InstantiationException ie) {
            errorMessage = ie.getMessage();
            return false;
        } catch (IllegalAccessException iae) {
            errorMessage = iae.getMessage();
            return false;
        }
        break;

    case MRJ_3_1:
        try {
            mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
            openURL = mrjFileUtilsClass.getDeclaredMethod("openURL", new Class[] { String.class });
        } catch (ClassNotFoundException cnfe) {
            errorMessage = cnfe.getMessage();
            return false;
        } catch (NoSuchMethodException nsme) {
            errorMessage = nsme.getMessage();
            return false;
        }
        break;

    default:
        break;
    }
    return true;
}