Class.getMethod using a superclass

I'm trying to use Class.getMethod to retrieve a particular method, but it keeps returning NoSuchMethodException s when i use code similar to this example.
try {
     Class<?> c = Class.forName("javax.swing.JFrame");
     Method m = c.getMethod("add",javax.swing.JButton.class);
catch(Exception e) {
     e.printStackTrace();
}I think it is unable to find the method because the add method takes a java.awt.Component, but is there any way around casting it to that? The method names and arguments are only provided at runtime, and the only solution I see is successive calls to Class.getSuperClass and testing the parameter over and over again to try to find the right method. This doesn't seem like a good solution, or even efficient, when considering the combinations you would have to attempt when given multiple parameters.
Is there a better way to solve this than that?

Hi,
I do not see a solution like the one you are looking for (automatic matching). But what may be easier than your proposed solution of successive calls to getMethod() with different combinations of parameter types, and each call throwing NoSuchMethodExceptions, may be something like:
- call getMethods()
- iterate over all methods found
- first matching names
- for each matching name, check parameter type (of course not equality, but whether your type would fit the type expected by the method)
- repeat for each parameter of current match
- repeat until matching method is found
Bye.

Similar Messages

  • Forums - How to use java.lang.Class.getMethod() and java.lang.reflect.Metho

    I have similar question. I am trying to invoke a method with no parameters. I don't know how to do that. Can someone please help.
    for example.
    I have 2 methods.
    public void setMethod(String strPut){
    this.strPut = strPut;
    public String getMethod(){
    return strPut;
    Method method = objRef.class.getMethod("setMethod", new Class[]{String.class});
    Object objReturn = method.invoke(sqlWhere, new Object[] {"any String"});
    I can invoke setMethod but I don't know how to invoke getMethod().

    Hi
    Try using something like this...
    CustomClass objCustomClass = new CustomClass ();
    Class customClass = objCustomClass.getClass ();
    Method m = customClass.getMethod ("getMethodName", (Class[])null);
    String strContent = (String) m.invoke (objCustomClass, null);
    Thanks and regards,
    Pazhanikanthan. P

  • How to use the Class.getMethod(String name, Class[] paramArrays)

    Hi,
    I've a problem with the .getMethod method. I've search solutions in the tutorials but I haven't found sorry.
    I'm trying to copy a method from a Class named carre in a reference named m. But I don't understand the second part of the parameters. How can I write parameters in a Class array ?
    Method m = Carre.class.getMethod("getYou", args) ; //It doesn't work, because args is a String array, not a Class array, my parameters would be double.
    Could you help me ? Thanks for answers.

    Class[] classArray = { new Double().getClass(), new String().getClass()};That's not what you want to write. That generates two objects unnecessarily. You should write:new Class[] { Double.class, String.class };

  • Can i create more than one attributes for the custom class created using java API

    Hello everyone,
    I have been creating class and its attributes programatically using java APIs, I want to know that is there any way to create multipal attributs for the same class in just one call of API with all the options for each attributes,
    thanks

    You can create a new class and define all of the Attributes at the time the class is created - this is the preferred way of creating classes. Use the addAttributeDefinition() method on ClassObjectDefinition. If you need to add attributes to existing classes, you can only add them one at a time (using the addAttribute() method on ClassObject).
    (dave)

  • Than how can i get java class by using it's class file?

    Hi
    After compilation of a java program, it creates a class file.
    After getting class file suppose class file has been deleted.
    Than how can i get java class by using it's class file?
    Thanks in advance.

    get a decompiler and run your class file through it--I'll assume you want the source code back and that you are not trying to recover a missing class file by attempting to use the class file that is missing--if it's missing, then I've not a clue on how to get it back by using what is already missing.
    BTW: many of your compilers have source control--if it does, just restore your missing file.

  • How to reference a class without using the new keyword

    I need to access some information from a class using the getter, but I don't want to use the new keyword because it will erase the information in the class. How can I reference the class without using the new keyword.
    ContactInfo c = new ContactInfo(); // problem is here because it erases the info in the class
    c.getFirstName();

    quedogf94 wrote:
    I need to access some information from a class using the getter, but I don't want to use the new keyword because it will erase the information in the class. How can I reference the class without using the new keyword.
    ContactInfo c = new ContactInfo(); // problem is here because it erases the info in the class
    c.getFirstName();No.
    Using new does not erase anything. There's nothing to erase. It's brand new. It creates a new instance, and whatever that constructor puts in there, is there. If you then change the contents of that instance, and you want to see them, you have to have maintained a reference to it somewhere, and access that instance's state through that reference.
    As already stated, you seem to be confused between class and instance, at the very least.
    Run this. Study the output carefully. Make sure you understand why you see what you do. Then, if you're still confused, try to rephrase your question in a way that makes some sense based on what you've observed.
    (And not that accessing a class (static) member through a reference, like foo1.getNumFoos() is syntactically legal, but is bad form, since it looks like you're accessing an instance (non-static) member. I do it here just for demonstration purposes.)
    public class Foo {
      private static int numFoos; // class variable
      private int x; // instance varaible
      public Foo(int x) {
        this.x = x;
        numFoos++;
      // class method
      public static int getNumFoos() {
        return numFoos;
      // instance method 
      public int getX() {
        return x;
      public static void main (String[] args) {
        System.out.println ("Foo.numFoos is " + Foo.getNumFoos ());
        System.out.println ();
        Foo foo1 = new Foo(42);
        System.out.println ("Foo.numFoos is " + Foo.getNumFoos ());
        System.out.println ("foo1.numFoos is " + foo1.getNumFoos ());
        System.out.println ("foo1.x is " + foo1.getX ());
        System.out.println ();
        Foo foo2 = new Foo(666);
        System.out.println ("Foo.numFoos is " + Foo.getNumFoos ());
        System.out.println ("foo1.numFoos is " + foo1.getNumFoos ());
        System.out.println ("foo1.x is " + foo1.getX ());
        System.out.println ("foo2.numFoos is " + foo2.getNumFoos ());
        System.out.println ("foo2.x is " + foo2.getX ());
        System.out.println ();
    }

  • Is it possible to call a class method using pattern in ABAP editor.

    Hi,
         Is it possible to call a class method using pattern in ABAP editor.
    Thank U for Ur time.
    Cheers,
    Sam

    Yes,
    Click patterns.
    Then choose Abap objects patterns.
    Click on the Tick
    It will give a new screen
    Here Give the name of the class first.
    Then the object (instance of the calss)
    And finally the method ..
    it will give you the pattern
    Hope this helps.

  • How do you know what classes to use ?

    Hello,
    This may sound daft - but how do you know what classes to use to do a particular task ? For example to do password-related stuff - how would I know which classes are all relevant to that ? Am I supposed to buy a book on the classes as the API documentation doesn't really tell you WHEN to use which classes.

    If you're using JSP, then your password field is likely going to be implemented in HTML. So that's nothing to do with Java. (And you can't use a JPassword field in a JSP page.) But when that field comes back to your server, you may be using Java to authenticate it. Even there, the question is not yet what Java method you are going to use, but what methodology. You could have a database to authenticate against, or an LDAP directory. Or you could have the web server use its built-in authentication, which means you don't have to do any Java coding at all. And there are other ways.
    So the question before yours is, how do you know what methodology to use? Again, that comes down to experience.

  • Converting byte[] to Class without using defineClass() in ClassLoader

    so as to de-serialize objects that do not have their class definitions loaded yet, i am over-riding resolveClass() in ObjectInputStream .
    within resolveClass() i invoke findClass() on a network-based ClassLoader i created .
    within findClass() , i invoke
    Class remoteClass = defineClass(className, classImage, 0, classImage.length);
    and that is where i transform a byte[] into a Class , and then finally return a value for the resolveClass() method.
    this seems like a lengthy process. i mean, within resolveClass() i can grab the correct byte[] over the network.
    then, if i could only convert this byte[] to a Class within resolveClass() , i would never need to extended ClassLoader and over-ride findClass() .
    i assume that the only way to convert a byte[] to a Class is using defineClass() which is hidden deep within ClassLoader ? there is something going on under the hood i am sure. otherwise, why not a method to directly convert byte[] to a Class ? the byte[] representation of a Class always starts with hex CAFEBABE, and then i'm sure there is a standard way to structure the byte[] .
    my core issue is:
    i am sending objects over an ObjectInputStream created from a Socket .
    at the minimum, i can see that resolveClass() within ObjectInputStream must be invoked at least once .
    but then after that, since the relevant classes for de-serialization have been gotten over the network, i don't want to cascade all the way down to where i must invoke:
    Class remoteClass = defineClass(className, classImage, 0, classImage.length);
    again. so, right now, within resolveClass() i am using a Map<String, Class> to create the following class cache:
    cache.put(objectStreamClass.getName(), Class);
    once loaded, a class should stay loaded (even if its loaded in the run-time), i think? but this is not working. each de-serialization cascades down to defineClass() .
    so, i want to short-circuit the need to get the class within the resolveClass() method (ie. invoke defineClass() only once),
    but using a Map<String, Class> cache looks really stupid and certainly a hack.
    that is the best i can do to explain my issue. if you read this far, thanks.

    ok. stupid question:
    for me to use URLClassLoader , i am going to need to write a bare-bones HTTP server to handle the class requests, right?Wrong. You have to deploy one, but what's wrong with Apache for example? It's free, for a start.
    and, i should easily be able to do this using the com.sun.net.httpserver library, right?Why would you bother when free working HTTP servers are already available?

  • Problem accessing servlet from java class which uses Basic Authentication

    "Hi,
    I am using weblogic 6.1 server. I am calling a servlet file from a class file using HttpURLConnection. This is the code below.
              String theUsername="B1A1Z1T2";
              String thePassword="hlladmin";
              String urlString="http://rsnetserver:113/hll/servlet/CallSSRUpload";
              String userPassword = theUsername ":" thePassword;
              String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes());
              try
                   URL url = new URL (urlString);
                   HttpURLConnection uc=(HttpURLConnection)url.openConnection();
                   int it = 0;
                   while ((it = encoding.indexOf('\n')) != -1
                        || (it = encoding.indexOf('\r')) != -1) {
                             encoding = encoding.substring(0, it)
                             encoding.substring(it 1);
                   uc.setRequestProperty("Authorization","BASIC " encoding);
                   uc.setRequestProperty("SOAPAction", url.toString());
                   System.out.println(uc.getResponseCode());
                   System.out.println(uc.getResponseMessage());
              catch(Exception io)
                   io.printStackTrace();
                   System.out.println("error message........" io.getMessage());     
    In web.xml I have d

    Hello,
    Could you post the stack trace?
    Thanks,
    Bruce
    Vijay Babu wrote:
    >
    "Hi,
    I am using weblogic 6.1 server. I am calling a servlet file from a class file using HttpURLConnection. This is the code below.
    String theUsername="B1A1Z1T2";
    String thePassword="hlladmin";
    String urlString="http://rsnetserver:113/hll/servlet/CallSSRUpload";
    String userPassword = theUsername ":" thePassword;
    String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes());
    try
    URL url = new URL (urlString);
    HttpURLConnection uc=(HttpURLConnection)url.openConnection();
    int it = 0;
    while ((it = encoding.indexOf('\n')) != -1
    || (it = encoding.indexOf('\r')) != -1) {
    encoding = encoding.substring(0, it)
    encoding.substring(it 1);
    uc.setRequestProperty("Authorization","BASIC " encoding);
    uc.setRequestProperty("SOAPAction", url.toString());
    System.out.println(uc.getResponseCode());
    System.out.println(uc.getResponseMessage());
    catch(Exception io)
    io.printStackTrace();
    System.out.println("error message........" io.getMessage());
    In web.xml I have d

  • How to create an object of our own class by using Class.forName()??

    how to create an object of our own class by using Class.forName()??
    plzz anser my qustion soon..

    Class.forName does not create an object. It returns a reference to the Class object that describes the metadata for the class in question--what methods and fields it has, etc.
    To create an object--regardless of whether it's your class or some other class--you could call newInstance on the Class object returned from Class.forName, BUT only if that class has a no-arg constructor that you want to call.
    Class<MyClass> clazz = Class.forName("com.mycompany.MyClass");
    MyClass mine = clazz.newInstance();If you want to use a constructor that takes parameters, you'll have to use java.lang.reflect.Constructor.
    Google for java reflection tutorial for more details.
    BUT reflection is often abused, and often employe when not needed. Why is it that you think you need this?

  • Which function module or class is used to import UNICODE files

    Hello all,
    Does anyone know which function module or global class is used to import files when the UNICODE check for the FILE port is ON?
    Thanks
    Ed Baker

    Hi,
    According to your requirement, you can prepare report through S_PH0_48000513 - Ad Hoc Query , you can get percentage from IT0007 in Ad Hoc query. first decide how many fields you want and then choose in selection criteria and generate the report.
    Thanks,
    Nirali P.

  • How many classes are used in java versions?...

    sun microsystems have released many java version...
    how many build in classes are used java version 1.2 ,1.3 etc ...

    Arun02006 wrote:
    sun microsystems have released many java version...
    how many build in classes are used java version 1.2 ,1.3 etc ...No idea why you should want to know... Anyway, download them and look inside the zip file that holds the source codes.
    You can download older Java versions here: [http://java.sun.com/products/archive/]

  • ScreenImage class to use clipboard

    Anyone know how instead of writing this out to a file, it can copy that image to the clipboard?
    thanks
    here is the ScreenImage class..
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class ScreenImage
          *  Create a BufferedImage for Swing components.
          *  The entire component will be captured to an image.
          *  @param      component Swing component to create image from
          *  @param      fileName name of file to be created or null
          *  @return     image the image for the given region
          *  @exception IOException if an error occurs during writing
         public static BufferedImage createImage(JComponent component, String fileName)
              throws IOException
              Dimension d = component.getSize();
              if (d.width == 0)
                   d = component.getPreferredSize();
                   component.setSize( d );
              Rectangle region = new Rectangle(0, 0, d.width, d.height);
              return ScreenImage.createImage(component, region, fileName);
          *  Create a BufferedImage for Swing components.
          *  All or part of the component can be captured to an image.
          *  @param      component Swing component to create image from
          *  @param      region The region of the component to be captured to an image
          *  @param      fileName name of file to be created or null
          *  @return     image the image for the given region
          *  @exception IOException if an error occurs during writing
         public static BufferedImage createImage(JComponent component, Rectangle region, String fileName)
              throws IOException
              boolean opaqueValue = component.isOpaque();
              component.setOpaque( true );
              BufferedImage image = new BufferedImage(region.width, region.height, BufferedImage.TYPE_INT_RGB);
              Graphics2D g2d = image.createGraphics();
              g2d.setClip( region );
              component.paint( g2d );
              g2d.dispose();
              component.setOpaque( opaqueValue );
              ScreenImage.writeImage(image, fileName);
              return image;
          *  Create a BufferedImage for AWT components.
          *  @param      component AWT component to create image from
          *  @param      fileName name of file to be created or null
          *  @return     image the image for the given region
          *  @exception AWTException see Robot class constructors
          *  @exception IOException if an error occurs during writing
         public static BufferedImage createImage(Component component, String fileName)
              throws AWTException, IOException
              Point p = new Point(0, 0);
              SwingUtilities.convertPointToScreen(p, component);
              Rectangle region = component.getBounds();
              region.x = p.x;
              region.y = p.y;
              return ScreenImage.createImage(region, fileName);
          *  Convenience method to create a BufferedImage of the desktop
          *  @param      fileName name of file to be created or null
          *  @return     image the image for the given region
          *  @exception AWTException see Robot class constructors
          *  @exception IOException if an error occurs during writing
         public static BufferedImage createDesktopImage(String fileName)
              throws AWTException, IOException
              Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
              Rectangle region = new Rectangle(0, 0, d.width, d.height);
              return ScreenImage.createImage(region, fileName);
          *  Create a BufferedImage from a rectangular region on the screen.
          *  @param      region region on the screen to create image from
          *  @param      fileName name of file to be created or null
          *  @return     image the image for the given region
          *  @exception AWTException see Robot class constructors
          *  @exception IOException if an error occurs during writing
         public static BufferedImage createImage(Rectangle region, String fileName)
              throws AWTException, IOException
              BufferedImage image = new Robot().createScreenCapture( region );
              ScreenImage.writeImage(image, fileName);
              return image;
          *  Write a BufferedImage to a File.
          *  @param      image image to be written
          *  @param      fileName name of file to be created
          *  @exception IOException if an error occurs during writing
         public static void writeImage(BufferedImage image, String fileName)
              throws IOException
              if (fileName == null) return;
              int offset = fileName.lastIndexOf( "." );
              String type = offset == -1 ? "jpg" : fileName.substring(offset + 1);
              ImageIO.write(image, type, new File( fileName ));
         public static void main(String args[])
              throws Exception
              final JFrame frame = new JFrame();
              final JTextArea textArea = new JTextArea(30, 60);
              final JScrollPane scrollPane = new JScrollPane( textArea );
              frame.getContentPane().add( scrollPane );
              JMenuBar menuBar = new JMenuBar();
              frame.setJMenuBar( menuBar );
              JMenu menu = new JMenu( "File" );
              ScreenImage.createImage(menu, "menu.jpg");
              menuBar.add( menu );
              JMenuItem menuItem = new JMenuItem( "Frame Image" );
              menu.add( menuItem );
              menuItem.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        //  Let the menu close and repaint itself before taking the image
                        new Thread()
                             public void run()
                                  try
                                       Thread.sleep(50);
                                       System.out.println("Creating frame.jpg");
                                       frame.repaint();
                                       ScreenImage.createImage(frame, "frame.jpg");
                                  catch(Exception exc) { System.out.println(exc); }
                        }.start();
              final JButton button = new JButton("Create Images");
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        try
                             System.out.println("Creating desktop.jpg");
                             ScreenImage.createDesktopImage( "desktop.jpg" );
                             System.out.println("Creating frame.jpg");
                             ScreenImage.createImage(frame, "frame.jpg");
                             System.out.println("Creating scrollpane.jpg");
                             ScreenImage.createImage(scrollPane, "scrollpane.jpg");
                             System.out.println("Creating textarea.jpg");
                             ScreenImage.createImage(textArea, "textarea.jpg");
                             System.out.println("Creating button.jpg");
                             ScreenImage.createImage(button, "button.jpg");
                             button.setText("button refreshed");
                             button.paintImmediately(button.getBounds());
                             System.out.println("Creating refresh.jpg");
                             ScreenImage.createImage(button, "refresh.jpg");
                             System.out.println("Creating region.jpg");
                             Rectangle r = new Rectangle(0, 0, 100, 16);
                             ScreenImage.createImage(textArea, r, "region.png");
                        catch(Exception exc) { System.out.println(exc); }
              frame.getContentPane().add(button, BorderLayout.SOUTH);
              try
                   FileReader fr = new FileReader( "ScreenImage.java" );
                   BufferedReader br = new BufferedReader(fr);
                   textArea.read( br, null );
                   br.close();
              catch(Exception e) {}
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

    guess i was making it harder than it really is...
         BufferedImage im = createImage (component );
         ImageClipboard.setClipboard( im );ImageClipboard:
    public  class  ImageClipboard {
        // This method writes a image to the system clipboard.
        // otherwise it returns null.
        public static void setClipboard(Image image) {
            ImageSelection imgSel = new ImageSelection(image);
            Toolkit.getDefaultToolkit().getSystemClipboard().setContents(imgSel, null);
        // This class is used to hold an image while on the clipboard.
        public static class ImageSelection implements Transferable {
            private Image image;
            public ImageSelection(Image image) {
                this.image = image;
            // Returns supported flavors
            public DataFlavor[] getTransferDataFlavors() {
                return new DataFlavor[]{DataFlavor.imageFlavor};
            // Returns true if flavor is supported
            public boolean isDataFlavorSupported(DataFlavor flavor) {
                return DataFlavor.imageFlavor.equals(flavor);
            // Returns image
            public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
                if (!DataFlavor.imageFlavor.equals(flavor)) {
                    throw new UnsupportedFlavorException(flavor);
                return image;
        // If an image is on the system clipboard, this method returns it;
        // otherwise it returns null.
        public static Image getClipboard() {
            Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
            try {
                if (t != null && t.isDataFlavorSupported(DataFlavor.imageFlavor)) {
                    Image text = (Image)t.getTransferData(DataFlavor.imageFlavor);
                    return text;
            } catch (UnsupportedFlavorException e) {
            } catch (IOException e) {
            return null;
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
    }thanks for the help!

  • Import java class that uses DbConnection

    How to import java class that uses DbConnection? I don't want to write my own PluginDataSource.
    It is possible to get Connection in imported java classes?

    This is not possible. Even connection used by individual PDS are only limited to those individaul PDS only and are not shared across them.
    Thanks
    Rohit

Maybe you are looking for