Reflect the class that implements Runnable

Hi,
I am implementing the reflection of the class that implements Runnable. In order to start a new thread I am trying to invoke "start()" method ( which is obviously not defined my class ) and I therefore I am getting "java.lang.NoSuchMethodException".
I am wondering is it possible at all to start a new thread on a reflected class?
thanks in advance.
{              Class refClass = Class.forName(className);
String methodName = "start";
Class[] types = new Class[1];
types[0] = Class.forName("java.util.HashMap");
Constructor cons = refClass.getConstructor(types);
Object[] params = new Object[5];
params[0] = new HashMap();
Method libMethod = refClass.getMethod(methodName, null);
libMethod.invoke(objType, null); }

Well, if we knew what it meant to "start a thread on a class" we could probably figure out how to "start a thread on a reflected class". If we knew what a "reflected class" was, that is.
In other words, it would help if you rephrased your question using standard terminology (and also explained why you want to do whatever it is you want to do).
But let's guess for now: If you have an object which implements Runnable then you start a thread to run that object like this:
Runnable r = // some object which implements Runnable
new Thread(r).start();Not what you wanted? Go ahead and clarify then.

Similar Messages

  • Question about methods in a class that implements Runnable

    I have a class that contains methods that are called by other classes. I wanted it to run in its own thread (to free up the SWT GUI thread because it appeared to be blocking the GUI thread). So, I had it implement Runnable, made a run method that just waits for the thread to be stopped:
    while (StopTheThread == false)
    try
    Thread.sleep(10);
    catch (InterruptedException e)
    //System.out.println("here");
    (the thread is started in the class constructor)
    I assumed that the other methods in this class would be running in the thread and would thus not block when called, but it appears the SWT GUI thread is still blocked. Is my assumption wrong?

    powerdroid wrote:
    Oh, excellent. Thank you for this explanation. So, if the run method calls any other method in the class, those are run in the new thread, but any time a method is called from another class, it runs on the calling class' thread. Correct?Yes.
    This will work fine, in that I can have the run method do all the necessary calling of the other methods, but how can I get return values back to the original (to know the results of the process run in the new thread)?Easy: use higher-level classes than thread. Specifically those found in java.util.concurrent:
    public class MyCallable implements Callable<Foo> {
      public Foo call() {
        return SomeClass.doExpensiveCalculation();
    ExecutorService executor = Executors.newFixedThreadPool();
    Future<Foo> future = executor.submit(new MyCallable());
    // do some other stuff
    Foo result = future.get(); // get will wait until MyCallable is finished or return the value immediately when it is already done.

  • Serializing a class that implements the Singleton pattern

    Hello,
    I am relatively new to Java and especially to serialization so the answer to this question might be obvious, but I could not make it work event though I have read the documentation and the article "Using XML Encoder" that was linked from the documentation.
    I have a class that implements the singleton pattern. It's definition is as follows:
    public class JCOption implements Serializable {
      private int x = 1;
      private static JCOption option = new JCOption();
      private JCOption() {}
      public static JCOption getOption() { return option; }
      public int getX() { return x; }
      public void setX(int x) { this.x = x; }
      public static void main(String args[]) throws IOException {
        JCOption opt = JCOption.getOption();
        opt.setX(10);
        XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("Test.xml")));
        encoder.setPersistenceDelegate(opt.getClass(),  new JCOptionPersistenceDelegate());
        encoder.writeObject(opt);
        encoder.close();
    }Since this class does not fully comply to the JavaBeans conventions by not having a public no-argument constructor, I have create a class JCOptionPersistenceDelegate that extends the PersistenceDelegate. The implementation of the instantiate method is as follows:
      protected Expression instantiate(Object oldInstance, Encoder out) {
           Expression expression = new Expression(oldInstance, oldInstance.getClass(), "getOption", new Object[]{});
            return expression;
      }The problem is that the resulting XML file only contains the following lines:
        <java version="1.5.0_06" class="java.beans.XMLDecoder">
            <object class="JCOption" property="option"/>
        </java> so there is no trace of the property x.
    Thank you in advance for your answers.

    How about this:
    import java.beans.DefaultPersistenceDelegate;
    import java.beans.Encoder;
    import java.beans.Expression;
    import java.beans.Statement;
    import java.beans.XMLEncoder;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    public class JCOption {
        private int x = 1;
        private static JCOption option = new JCOption();
        private JCOption() {}
        public static JCOption getOption() { return option; }
        public int getX() { return x; }
        public void setX(int x) { this.x = x; }
        public static void main(String args[]) throws IOException {
          JCOption opt = JCOption.getOption();
          opt.setX(10);
          ByteArrayOutputStream os = new ByteArrayOutputStream();
          XMLEncoder encoder = new XMLEncoder( os );
          encoder.setPersistenceDelegate( opt.getClass(), new JCOptionPersistenceDelegate() );
          encoder.writeObject(opt);
          encoder.close();
          System.out.println( os.toString() );
    class JCOptionPersistenceDelegate extends DefaultPersistenceDelegate {
        protected Expression instantiate(Object oldInstance, Encoder out) {
            return new Expression(
                    oldInstance,
                    oldInstance.getClass(),
                    "getOption",
                    new Object[]{} );
        protected void initialize( Class<?> type, Object oldInstance, Object newInstance, Encoder out ) {
            super.initialize( type, oldInstance, newInstance, out );
            JCOption q = (JCOption)oldInstance;
            out.writeStatement( new Statement( oldInstance, "setX", new Object[] { q.getX() } ) );
    }   Output:
    <?xml version="1.0" encoding="UTF-8"?>
    <java version="1.5.0_06" class="java.beans.XMLDecoder">
    <object class="JCOption" property="option">
      <void property="x">
       <int>10</int>
      </void>
    </object>
    </java>

  • Reading the Interfaces name which the class is implementing in a COM dll is implementing.

    Hi All,
    I'm using .NET Reflection to read a COM dll. I'm able to fetch the classes that are present in the dll. But I would like to know interface name which this class is implementing.
    For a .NET dll we can know the name of class's implementing interface name using the <classname>.BaseType.Name property.
    How can I know the interface name which this class is implementing (if any).
    Please let me know how to do this for a COM dll.
    Thanks in advance,Satish
    Thanks, Satish Bommideni "Success usually comes to those who are too busy to be looking for it."

    Hi,
    Thanks for the reply.
    I'm reading the COM assembly using the methods available in oleaut32.dll.
    Also I've imported the namespaces
    System.Runtime.InteropServices.ComTypes;
    System.Runtime.InteropServices;
    to use its respective methods and thus I'm able to read it's classes.But donot know what property to check for this class's interface.
    Kindly let me know if you need any further information.
    Thanks, Satish Bommideni "Success usually comes to those who are too busy to be looking for it."

  • Show the class that is loading

    Hi i have an applet that take a lot of classes to load and i have a splash screen that display the user a little image with a JProgressBar with the setIndeterminate() to true. For this i don't care, but what i want is to do like acrobat software that display all plugin that is loading. So when the splashscreen start i want it to display all classes that is loading at the moment the jre load it.
    Is there a dynamic way? Cause i know i can use
    Class thatClass = Class.forName("TheClassToLoad");
    theObject = thatClass.newInstance();
    but each time i will have to add a new class i will add to add these line... so i want something that will know which classes the java runtime is loading and display the name to the user
    thx

    maybe this could help
    it's a class i had to load the applet, that give me the possibility to start my splash screen before the user dl all my big applet
    import javax.swing.JApplet;
    import java.applet.AppletStub;
    import java.awt.Graphics;
    import java.awt.GridLayout;
    import javax.swing.JLabel;
    import javax.swing.JEditorPane;
    public class QuickLoader extends JApplet implements Runnable, AppletStub
        String appletToLoad;
        JLabel label;
        Thread appletThread;
        public void init()
            appletToLoad = getParameter("applet");
            if (appletToLoad == null)
                label = new JLabel("No applet to load.");
            else
                label = new JLabel("Please wait - loading applet " + appletToLoad);
            getContentPane().add(label);
        public void run()
            if (appletToLoad == null)
                return;
            try
                // Get the class for the applet we want
                Class appletClass = Class.forName(appletToLoad);
                // Create an instance of the applet
                JApplet realJApplet = (JApplet)appletClass.newInstance();
                // Set the applet's stub - this will allow the real applet to use
                // this applet's document base, code base, and applet context.
                realJApplet.setStub(this);
                // Remove the old message and put the applet up
                getContentPane().remove(label);
                // The grid layout maximizes the components to fill the screen area
                // - you want the real applet to be maximized to our size.
                getContentPane().setLayout(new GridLayout(1, 0));
                // Add the real applet as a child component
                getContentPane().add(realJApplet);
                // Crank up the real applet
                realJApplet.init();
                realJApplet.start();
            catch (Exception e)
                // If we got an error anywhere, print it
                label.setText("Error loading applet.");
            // Make sure the screen layout is redrawn
            getContentPane().validate();
        public void start()
              appletThread = new Thread(this);
              appletThread.start();
        public void stop()
              appletThread.interrupt();
              appletThread = null;
        // appletResize is the one method in the JAppletStub interface that
        // isn't in the JApplet class. You can use the applet resize
        // method and hope it works.
        public void appletResize(int width, int height)
              resize(width, height);
    }bu i don't know how to integrate your code to load all my classes correctly and be able to display the name of the class that are loading
    thx for help

  • Transform a class that implements JPanel into a bean.

    I'd to create a bean, from a class that implements JPanel, that in fact is a custom component.
    How can I create a bean?
    I have absolutely no idea about beans.
    What can make beans for me?
    I know a lot about the theory of ejb, is this what I need?
    I'm quite confused, please make me see the light!!!!!
    Thanks.

    Hi Daniel!
    To answer your question short as possible:
    Java -Beans are reusable code - components,
    similar to VB Active -X components,
    which you can use when developing your own
    applications.
    Beans can have a graphic user interface, so you
    can use builder tools like JBuilder or Beanbox
    to show them graphically in a designer.
    You can modify them about their properties,
    mostly shown in a special property window of a
    builder tool.
    It's really not very hard to create your own beans,
    the only thing you have to do is to pack all the
    classes which make the bean into a jar file.
    Then you can import the bean with the builder
    and it will be shown.
    The jar manifest file needs to look like for example:
    Manifest-Version: 1.0
    Name: BeanClock.class
    Java-Bean: True
    All the properties are implemented by public property-get
    and property-set methods, in order to show them in the property window.
    Java is doing that by introspection.
    Hope, this makes it a little bit clearer for you!

  • Performance wise which is best extends Thread Class or implement Runnable

    Hi,
    Which one is best performance wise extends Thread Class or implement Runnable interface ?
    Which are the major difference between them and which one is best in which case.

    Which one is best performance wise extends Thread Class or implement Runnable interface ?Which kind of performance? Do you worry about thread creation time, or about execution time?
    If the latter, then don't : there is no effect on the code being executed.
    If the former (thread creation), then browse the API Javadoc about Executor and ExecutorService , and the other execution-related classes in the same package, to know about the usage of the various threading/execution models.
    If you worry about, more generally, throughput (which would be a better concern), then it is not impacted by whether you have implemented your code in a Runnable implementation class, or a Thread subclass.
    Which are the major difference between them and which one is best in which case.Runnable is almost always better design-wise :
    - it will eventually be executed in a thread, but it leaves you the flexibility to choose which thread (the current one, another thread, another from a pool,...). In particular you should read about Executor and ExecutorService as mentioned above. In particular, if you happen to actually have a performance problem, you can change the thread creation code with little impact on the code being executed in the threads.
    - it is an interface, and leaves you free to extend another class. Especially useful for the Command pattern.
    Edited by: jduprez on May 16, 2011 2:08 PM

  • HELP?! a class that implements .....  : java.util.Vector

    My instructions say this:
    In the constructor, create the collection object (Since java.util.List is an interface, you will need to instantiate a class that implements this interface: java.util.Vector or java.util.LinkedList or java.util.ArrayList).
    I know, this IS a homework assignment - I am not sure how to go about this. I DO have code so far up to this point, can anyone help?
    import dLibrary.*;
    import java.awt.Color;
    * @author Rob
    * @version 8/18/03
    public class PhrasesII extends A3ButtonHandler
            private A3ButtonWindow win;
            private ATextField stringAcceptor;
            private ALabel listOstrings;
            private ALabel inputString;
            private ALabel status;
            private java.awt.List display;
            private java.util.List collection;
    public PhrasesII()
            win = new A3ButtonWindow(this);
            stringAcceptor= new ATextField (50,420,200,25);
            stringAcceptor.place(win);
            listOstrings = new ALabel(100, 10, 100, 380);
            listOstrings.setFontSize(10);
            listOstrings.setText("List of Strings:");
            listOstrings.place(win);
            inputString = new ALabel(50,400,200,25);
            inputString.setFontSize(10);
            inputString.setText("Input String:");
            inputString.place(win);
            display = new java.awt.List();
            display.setLocation(200, 100);
            display.setSize(200, 250);
            display.setBackground(Color.lightGray);
            win.add(display, 0);
            win.setLeftText("Save");
            win.setMidText("Display");
            win.setRightText("Discard");
            win.repaint();
      public void leftAction()
        public void midAction()
        public void rightAction()

    I am getting a " can't resolve symbol" when I do thisYou have to either import java.util.ArrayList or specify it fully, e.g., "new java.util.ArrayList()".
    Is that the line that is causing you problems? The error message should give the line number.
    my instructions also say I have to use "interface
    java.util.List when declaring your reference" so I am
    confused about using "= new ArrayList();"What they're saying is that you want code like this:
    private java.util.List frogs;    // this is the reference declaration
    //... later on...
    frogs = new java.util.ArrayList();  // this isn't a declarationWhat this means is that when you declare a field or variable, you should declare its type to be an interface.
    But when you actually instantiate a value for that variable, then you should use a concrete class that implements that interface. (You have to; interfaces can't be instantiated.)
    This is good programming style for reasons I don't have the space to explain here.

  • Importing classes that implement jsp tags

              I was making a custom JSP tag library. The tag functionality was implemented in
              a class called, lets cay ClassA. I made the tld file and put it under the WEB-INF
              directory. The class which implemented the functionality was placed under WEB-INF/classes
              directory. I had the imported the tag library using the taglib directive. I was
              getting an error which said "cannot resolve symbol". But when I in the JSP file
              I imported the class file which implemented the taglib functionality the error
              vanished. Is it necessary to import the class files even if the taglib is imported.
              The documentation does not say so. Or is there some configuration I have to make.
              

    I think was a side effect of the .jsp changing redeploys the web app in 6.0.
              When the web app was redeployed your directory structure was reread and thus
              it found your .tld.
              Sam
              "bbaby" <[email protected]> wrote in message
              news:3b422db7$[email protected]..
              >
              > I was making a custom JSP tag library. The tag functionality was
              implemented in
              > a class called, lets cay ClassA. I made the tld file and put it under the
              WEB-INF
              > directory. The class which implemented the functionality was placed under
              WEB-INF/classes
              > directory. I had the imported the tag library using the taglib directive.
              I was
              > getting an error which said "cannot resolve symbol". But when I in the JSP
              file
              > I imported the class file which implemented the taglib functionality the
              error
              > vanished. Is it necessary to import the class files even if the taglib is
              imported.
              > The documentation does not say so. Or is there some configuration I have
              to make.
              >
              >
              

  • Need info on the class that is used for BUILHEADER Genil query

    Hi All,
    Can some one pls let me know the class that is called by executing the query BUILHEADER.
    I m facing a strange error, everytime when i search and open any account other than sold to party in WEBUI, I am noticing soldto party in the Roles Assignment block. But the business partner in the backend is not having hte role sold to party. i am not finding how this defaulting is happening automatically.
    Any pointers/clues on this will be very very helpful.
    Thanks,
    Udaya

    Hello Udaya,
    The class is CL_BUIL_HEADER Copy it and redifine method GET_RESULT_TABLE.
    then goto SPRO I'm not remember exactly where you should change the SAP class into yours.
    Sorry it was on ICWC5.0 and not CRM2007
    Eli Steklov
    Edited by: Eli Steklov on Jul 16, 2008 3:52 PM

  • "The class being compiled does not match the class that was imported"

    ----------Actions on timeline in
    sixSpices/updateSite/updateSite.fla----------
    import com.sixspices.updater.view.*;
    var calDrawer:CalendarView = new CalendarView(); //Listener /
    view
    ----------sixSpices/com/sixspices/updater/view/CalendarView.as
    file----------
    class CalendarView {
    public function CalendarView(){
    public function onRecieveData(listOfEvents:Array) {
    displayEvents(listOfEvents);
    public function displayEvents(listOfEvents:Array):Void {
    trace(listOfEvents);
    When I test the movie (updateSite.swf) in flash, it gives me
    the error:
    The class being compiled, 'CalendarView', does not match the
    class that was imported,
    'com.sixspices.updater.view.CalendarView'.

    Here is my file structure:
    sixSpices
    -->updateSite
    -->-->updateSite.fla
    -->-->updateSite.swf
    -->com
    -->-->sixSpices
    -->-->-->updater
    -->-->-->-->view
    -->-->-->-->-->Calendar.as
    If I move updateSite.fla to the folder sixSpices so that
    "com" is in the same folder as it, I get the same error.
    The following works with no problems (no similar error):
    ----------Actions on timeline in
    sixSpices/updateSite/updateSite.fla----------
    import com.sixspices.updater.model.*;
    var calModel:CalendarOverview = new CalendarOverview();
    //Broadcaster / model
    ----------sixSpices/com/sixspices/updater/model/CalendarOverview.as
    file----------
    import com.sixspices.updater.model.*;
    import mx.utils.Delegate;
    import mx.events.EventDispatcher;
    class CalendarOverview {
    public function CalendarOverview(){
    }

  • How can I know a class which implements Runnable interface has terminated?

    Hello! I have a class which has implements Runnable interface, while I want to execute some operation when the thread has terminate in multithread enviroment.How can I know the thread has terminated?Does it give out some signal?Cant I just call my operation at the end of the run() method?

    I want to execute some operation when
    the thread has terminate in multithread enviroment....
    Cant I just call my operation at the end
    of the run() method?Sure. Before run() ends, invoke that other operation.
    How
    can I know the thread has terminated?Does it give out
    some signal?Not that I'm aware of, but you can do what you described above, or I believe a different object can call isAlive on the thread.

  • Modifying a Class that implements Serializable

    I have a class LDAPUser
    import java.io.*;
    public class LDAPUser implements java.io.Serializable{
         private java.lang.String name;
         private java.lang.String userID;
         private java.lang.String associateNumber;
    public LDAPUser() {
         super();
    public boolean equals(Object o) {
         if (o == this)
         return true;
         if (!(o instanceof LDAPUser))
         return false;
         return (((LDAPUser)o).getAssociateNumber().equals(this.getAssociateNumber()));
    public java.lang.String getAssociateNumber() {
         if(associateNumber == null){
              return getUserID();
         return associateNumber;
    public java.lang.String getName() {
         return name;
    public java.lang.String getUserID() {
         return userID;
    public void setAssociateNumber(java.lang.String newAssociateNumber) {
         associateNumber = newAssociateNumber;
    public void setName(java.lang.String newName) {
         name = newName;
    public void setUserID(java.lang.String newUserID) {
         userID = newUserID;
    It works fine.
    I needed to add functionality to it. These were the modifications.
    private java.lang.String distinguishedName;
    private boolean validUser;
    public java.lang.String getDistinguishedName() {
         return distinguishedName;
    public boolean isValidUser() {
         return validUser;
    public void setDistinguishedName(java.lang.String newDistinguishedName) {
         distinguishedName = newDistinguishedName;
    public void setValidUser(boolean newValidUser) {
         validUser = newValidUser;
    I am using visual age for java and in the Test environment the changes work fine.
    When I promote the changes to our application server (websphere) the changes are not there. I get a method not found error and though trial and error have identified that the server is not actually using the class from the jar. I have removed any other occurences of the class from the server.
    My question is if I change a Serializable class how do I make those changes take affect (thorough better coding) and for right now, where is this "old instance" of my class coming from and how do I get rid of it.
    Thanks in Advance,
    Jason Grieve

    If the server is running than the class might be already loaded through the class loader, so it wont be load again.
    this unless you use hot deployment, which you have to figure how it is being handled in your srver.
    Doron

  • Abstract Class that implements Comparable

    I am trying to understand how a comparable interface works with an abstract class. Any help is greatly appreciated.
    I have a class ClassA defined as follows:
    public abstract class ClassA implements Comparable I have a method, compareTo(..), within ClassA as follows:
    public int compareTo(Object o) I have a sub-class ClassB defined as follows:
    public class ClassB extends ClassAI am receiving a compile error:
    Class must implement the inherited abstract method packagename.ClassA.compareTo(Object)
    Should or can the compareTo be abstract in ClassA and executed in ClassB? Just not sure how this works.

    ???? if you are inheriting from an abstract class your subclass must implement methods that were declared in the parent (abstract) class but not implemented
    When in doubt, refer to the Java Language Specification..

  • Portlets development: When to use the class that extends PortletBridge...

    When I create some Portlet (.jspx based) JDeveloper generate some resources. One of those is a class (with the name that I´ve configured) that extends PortletBridge...
    Ok. So, I want to know if I use JSF standards should I put my actions into this class or should I create another Managed bean to handle that? What to do with this generated class?
    Thank you.

    So you want to create a portlet that uses JSF instead of JSP?
    You can JDev do that for you. When you create a new portlet there is a step where you can specify the default page for the portlet mode (view, edit).
    On the right hand side you can select ADF JSF (or something like that).
    JDev will then create a class that extends the PortletBridge class and you don't have to do anything more. Just edit the jspx like it's a normal page.

Maybe you are looking for

  • My mail wont open.

    How can I open mail. I click on the mail icon and nothing happens

  • How can I get rid of formatting marks in a doc that is copied and pasted into word; these marks don't show up in Safari.

    When copying and pasting text from an article into Word, formatting marks appear in the copied text that don't appear if I cut and paste from Safari to Word. This started several months ago, perhaps even a year ago. I assume it's a FF issue since it

  • View Deleted Sales Order by material

    I need to know in that sales order has been a material because when we run MRP, system creates purchase requisition for requeriments of sales order, ok? But, after if user deletes sales order, the purchase requisition created is incorrect but purchas

  • Group ID, ID-Mapping, storage of data

    Hi, I've got a question concerning <b>where which data or data attributes are being stored in the (re-)distribution of cleansed master data</b>. Please have a look at the following example: In my understanding MDS extracts Master Data (only special i

  • Can't install PI_BASIS 2006_1_700 Patch 1~9

    Dear consultant,   I have installed PI_BASIS 2006_1_700(51032426) using SAINT and I want to install SP 1~9(KIPYM01). I uncompress all car files, but can't select it via SPAM->PI_BASIS. What happen?