How to access class stored as value in TreeMap by reflection?

Hello

I have the following two files Buffet.java and Restaurant.java. Restaurant uses reflection to load the class Buffet and I want to be able to call the method fruitMessage() to each fruit in the TreeMap.

Thank you
Jimmy


File buffet. Java
import java.util.*;

public class Buffet {
     Map<String, Fruits> alist2 = new TreeMap<String, Fruits>();
     public void addFruits() {
          alist2.put("a", new Fruits("apple"));
          alist2.put("b", new Fruits("orange"));
          alist2.put("c", new Fruits("pear"));
     }
}

class Fruits {
     public String fruit;
     public Fruits(String str) {
          this.fruit = str;
          System.out.println("this is a " + str);
     }
     public void fruitMessage() {
          System.out.println("the "+fruit+" is delicious");
     }
}
File restaurant. Java
import java.lang.reflect.*;
import java.net.*;
import java.io.File;
import java.util.*;

public class Restaurant {
     public Restaurant() {
          try {
               File myFile = new File("Buffet.java");
               URL myURLFile = myFile.toURI().toURL();  
               URLClassLoader cloader = URLClassLoader.newInstance(new URL[] {myURLFile });
               Class myClass = cloader.loadClass("Buffet");
               Constructor c = myClass.getConstructors()[0];

               Object newObj = c.newInstance(new Object[]{});
               Method method = myClass.getMethod("addFruits");
               Object obj = method.invoke(newObj, new Object[] {});
     
               Field f = newObj.getClass().getDeclaredField("alist2");
               Map m = (Map) f.get(newObj);
               
               ParameterizedType pt = (ParameterizedType)newObj.getClass().
                                                  getDeclaredField("alist2").getGenericType();
               Type tt = pt.getActualTypeArguments()[1]; // has the Fruits type
               
               Set<Map.Entry<String, Object>> set = m.entrySet();
               for (Map.Entry<String, Object> me : set) {
                    String key = me.getKey();
                    Object value = me.getValue();

                                // ???? how to get call the fruitMessage() method ?????????
               }
          } catch(Exception e) {
               e.printStackTrace();
          }
     }

     public static void main(String [] args) {
     new Restaurant();
     }
}
Published by: user8400807 on April 6, 2012 15:34

Edited by: EJP 04/07/2012 10:09: adding the {code} tags: Please use

It reads the file in java

No it isn't, it's load classes as a JAR file. Do not call your .java files JAR, otherwise someone will try to compile them and get a bad surprise. Eventually you even confuse yourself.

Type tt = pt.getActualTypeArguments()[1];
Class fc = (Class)tt; // i.e. Fruit.class
Method fruitMessage = fc.getMethod("fruitMessage");
// ...
m.invoke(value);

But I don't understand. If you know the name of the method, why you don't know the class of the object?

Tags: Java

Similar Questions

  • How to access image stored in Blackberry using Bitmap.getBitmapResource ()?

    I want to access an image stored in Blackberry, say instead of "store/home/user/image.png".

    Now I can access the image as,

    String filePath = "file:///store/home/user/image.png;
    Bitmap image = Bitmap.getBitmapResource(filePath);
    BitmapField bitmapField = new BitmapField(image, BitmapField.FOCUSABLE);
    

    OR

    I have to access

    String filePath = "file:///store/home/user/image.png;
      FileConnection fconn = (FileConnection)Connector.open(filePath, Connector.READ);
      if (fconn.exists())
      {
                    ........
                    ........                           
    
         input.close();
         fconn.close();                            
    
      }
    

    I am able to access the image using the second way, but I want to know that can I access using 'Bitmap.getBitmapResource (filePath)?

    None

  • How to access point password value

    I created two points where the element type is password.

    Name of the element is P1_PASS1 and P1_PASS2I

    In the PL/SQL code, I can't access the values ITEM P1_PASS1 and P1_PASS2

    I tried to debug too, but there is no value printed in the debug log.

    Actually, I want to call to a PL/SQL procedure where I need to pass the value as a variable. How to access values of these elements of password? I use 5 APEX

    Start

    wwv_flow. Debug ('test123');

    wwv_flow. Debug ('pass' |) V ('P1_PASS1'));

    p_testproc (V ('P1_PASS1'),: P1_RETVAL);

    end;

    If your problem is fixed?

  • How does Flex access classes AS3 files?

    How does Flex access classes AS3 files?  They are in the specific folder?  Is there such a thing as the class path?

    Thank you.

    Doug

    If you use the Flash as a programming language, it would be exactly the same. Packages with classes in there.

  • How to access a value of "List of values" by giving a name?

    I have a "list of values" defined in my report of BI. It includes a list of pairs of value of the label.

    I've defined a parameter: p_Value for the definition of "List of values" above. This parameter is used in the definition of sql data source to filter the query results. I set up a model that has a table which shows all the parameters used for filtering the results of the query. If I give <? $p_Value? > in the model, then the value parameter is returned to this subject. But I want the 'name' of the setting, not the value. Can someone tell me how to access the name of the parameter that refers to a value in the definition of "value list"?

    option 1:
    You can get the value of the DB in the sql report?

    You have the code inside the report query, if you can get the decoded form of value which

    option 2:
    create another parameter, LOV and query, make the most hidden and use the first: param_1_value in the lov query in the second param and decoding the value.

    Now you can check the: PARAM_2_value in the model that will be decoded value.

  • How to access the value of the point of application in javascript

    How to access the value of the point of application in javascript?

    Hello

    A way

    var myVariable = '&MY_APP_ITEM.';
    

    BR, Jari

  • How to access the inner class fields in refleciton?

    I have:
    class Outer {
        class Inner {
            int field;
        }
        Inner inner;
    }
    I use reflection to get the Outer.field field and recognize that it is a reference to the inner class. What should I do to get the inner.field (or something that looks remotely like this at Inner.field)?

    We would like to

    Well, precedent is too messy for me even follow my example. I've simplified it, and I think I found where my error was. I suspect that you were doing a similar error:

    package scratch;
    
    import java.lang.reflect.Field;
    
    public class Scratch {
    
      public static void main(String[] args) throws Exception {
        new Scratch().go();
      }
    
      void go() {
        Outer1 o1;
    
        Field[] fields = Outer1.class.getDeclaredFields ();
    
        for (Field field : fields) {
    
          final String fn = field.getName ();
          final Class ft = field.getType ();
          final Class fc = field.getClass ();
          final Class fdc = field.getDeclaringClass ();
    
          System.out.println ();
    
          System.out.println ("Outer1 field : " + fn);
    
          System.out.println ();
    
          System.out.println ("field's class (field.getType()) : " + ft.getName());
          System.out.println ("field.getType().isMemberClass() (" + ft.getName() +" isMemberClass()) : " + ft.isMemberClass ());
          System.out.println ("field.getType(). getDeclaringClass() (" + ft.getName() + "'s declaring class) : " + fdc);
    
          System.out.println ();
    
          System.out.println ("field.getClass()) : " + fc.getName());
          System.out.println ("field.getClass().isMemberClass() (" + fc.getName() +" isMemberClass()) : " + fc.isMemberClass ());
          System.out.println ("field.getClass().getDeclaringClass() (" + fc.getName() + "'s declaring class) : " + fc.getDeclaringClass ());
    
          System.out.println ();
    
          System.out.println ("Note the difference between Field.getClass() (" + field.getClass () + ") and Field.getType() (" + field.getType() + ")");
    
          System.out.println ();
        }
      }
    }
    
    class Outer1 {
      class Inner1 {
      }
    
      Inner1 i1;
    }
    
    Outer1 field : i1
    
    field's class (field.getType()) : scratch.Outer1$Inner1
    field.getType().isMemberClass() (scratch.Outer1$Inner1 isMemberClass()) : true
    field.getType(). getDeclaringClass() (scratch.Outer1$Inner1's declaring class) : class scratch.Outer1
    
    field.getClass()) : java.lang.reflect.Field
    field.getClass().isMemberClass() (java.lang.reflect.Field isMemberClass()) : false
    field.getClass().getDeclaringClass() (java.lang.reflect.Field's declaring class) : null
    
    Note the difference between Field.getClass() (class java.lang.reflect.Field) and Field.getType() (class scratch.Outer1$Inner1)
    

    field.getClass () does NOT get the class of the field. It get the class of the field object that points to the field reference variable, which is always java.lang.reflect.Field. To get the class of the field, use field.getType ().

    Do you see the difference?

    Edited by: jverd February 5, 2011 17:18

  • How to access info child movieclip to an object in a table?

    Hello

    I created a whole bunch of clips dynamically.

    I gave a name based on a variable number to each item:

    MC. Name = "mc" + i;

    I also use addChild to add some dynamic text fields to each movieClip and named myText1 myText2.

    Then I push each movieClip object in a table:

    myArray.push (mc);

    When I have the movieClips addChild, they display fine, complete with each textField.  And if I use the following loop to find the name of each element of the array, I get:

    for (var i = 0; i < myArray.length; i ++)

    {

    trace (myArray [i]. (Name)

    }

    output:

    MC1

    MC2

    MC3

    MC4

    etc.

    What I want now is to be able to access text fields in each movieclip in the table.  However, I get errors when I try in different ways.  For example:

    for (var i = 0; i < myArray.length; i ++)

    {

    trace (myArray [i].myText1.Text);

    }

    gives error: a term is undefined and has no properties.

    How to access the values and the content of the children of the movieClip objects that are stored in the tables?

    Thank you

    Shaun

    For some reason, dynamically added children cannot be targeted like that.  If you have added the textfields dynamically, you may need to use the getChildByName() target.  It depends in part on how you created and whether or not you have direct access to them.  Aside from that, you can also assign the textfields to the variables that you create for the mc and target those who by their names of variables.

    These two approaches demos the following:

    var mc:MovieClip = new MovieClip();
    addChild (mc);

    var tf:TextField = new TextField();
    TF. Text = "this is the text";
    mc.addChild (tf);

    first way

    TF. Name = "tfield."
    trace (TextField (MC.getChildByName ("TField")). (Text);

    second way

    MC.tfid = tf;
    trace (MC.tfid.Text);

    You can also store the textfields in the tables are created and they have direct access to them with the need to target the mc... the index must be the same as the one you use for the mc anyway.

  • How to access the BPM 11 g load useful or process varibles in the workflow of ADF

    I'm trying to view/edit the data in a user interface that is linked to a database by using a foreign key, requestId. The foreign key comes from a BPM process where it is spent in the workflow, a human task. The foreign key comes process variables or values of payload. I know that I can simply load the payload in BPM with the data in the tables, but I'm looking for a better solution use the ADF business components to view and edit data directly in the user interface.

    The BPM process uses a web service to start the process. Web services takes a primary key as a parameter to reference a column in the database table. The data is pre-filled with content and a primary key reference. The first activity is an activity of the user. I want the workflow behind the user activity to accept this primary key and use to locate the line in the database, so related views of the database delimited ADF business components can work to present the data in the user interface.

    I tried two approaches to the problem. The first uses the setCurrentRowWithKeyValue operation. The other changes the SQL where clause, used by the ADFbc iterator only returns one row for the given requestId. Both of these approaches fail to work because I don't know how to access the load BPM or variable data entering the workflow. Here is the piece of code that I used to try to define the row using the value of setCurrentRowWithKey:

    public String setRequestId() {}

    FacesContext context = FacesContext.getCurrentInstance ();
    Object requestObj = context.getApplication () .evaluateExpressionGet)
    context, "#{bindings."(, Number.class) RequestId.inputValue "};
    If (requestObj is nothing)
    Returns a null value.
    RequestId number;
    requestId = (number) requestObj;

    ITR DCIteratorBinding = (DCIteratorBinding)

    getBindings () .get ("PatfRequestHdrView1");

    itr.setCurrentRowWithKeyValue (requestId.toString ());

    Returns a null value.

    I didn't get very far with the second approach, change SQL where clause, because I do not know Groovy. I think I need something like:

    adf.object.viewObj.RequestId. but it is not a viewObject associated with BPM data, so I don't know that this particular expression will not work.

    Any help you can give me is greatly appreciated.

    Kind regards
    Mark

    Try this code in your method:

    FacesContext context = FacesContext.getCurrentInstance ();
    String ctx = (String) context.getApplication () .evaluateExpressionGet (context, "#{pageFlowScope.bpmWorklistContext}", String.class);
    String tskId = (String) context.getApplication () .evaluateExpressionGet (context, "#{pageFlowScope.bpmWorklistTaskId}", String.class);
    IWorkflowServiceClient workflowSvcClient = WorkflowService.getWorkflowServiceClient ();
    ITaskQueryService wfQueryService = workflowSvcClient.getTaskQueryService ();
    IWorkflowContext wfContext = wfQueryService.getWorkflowContext (ctx);
    Task myTask = wfQueryService.getTaskDetailsById (wfContext, tskId);
    XMLElement xmlPayload = (XMLElement) myTask.getPayloadAsElement ();
    get the payload as a string simple, useful for debugging
    java.io.StringWriter writer = new java.io.StringWriter ();
    xmlPayload.print (writer);
    String payloadAsString = writer.toString ();
    extract payload values: use methods in Oracle XDK

    See also this post:

    The task of reading by program details

  • Re: How to access the restore partition on satellite Pro L300?

    Is there a partition on this laptop with the prog of recovery on it, and how to access it, I tried to use F1, 2, 8, 9 and 1 and 2, without success, all I get is "a disk error occurred, press control + alt + delete to restart.

    Help please?

    Don t start installation of recovery if laptop s not connected to the power supply current. It is very important.

    If you want to check the user s in any case manuals, you can download it from http://eu.computers.toshiba-europe.com/innovation/download_manuals.jsp

    Blue screen?
    Please explain exactly what are you doing and what exactly happens.
    One last thing. Before do you anything enter parameters of the BIOS (F2 at startup) and the value of the default BIOS.

  • How to access a shared file on my RN212 NAS remotely from another program?

    I've looked everywhere trying to find how to access a shared file on my RN212 NAS remotely from another program (kodi) on my iPhone 6 more remotely, away from home. I tried to FTP, UPnP, HTTP, etc. anything and it's driving me crazy! I run the program kodi from my phone for watching videos stored on my SIN, I have a router NightHawkR7000 and believe that I am fairly warned to get this figured out, but apparently not lol I have all the correct ports forwarded, but perhaps I'm missing a step somewhere. Any help on this would be much appreciated!

  • How to access objects collection

    How to access the collections of objects for example ReportSections report? I can access ReportSection, but not his collection...

    Reference: http://www.ni.com/pdf/manuals/372844e.pdf

    Maybe you don't understand exactly what section of the report is. According to the help:

    Use this class objects to store, update and transfer reports. You typically use the ReportSection objects to avoid creating copies of a report that the report is transferred between the generator of reports, process, Report and ReportView control object models. You can create a new ReportSection object by calling the Report.NewReportSection method. ReportSection objects can contain other ReportSection objects.

    As a general rule, a process template creates and updates the ReportSection object and assigns to the report object by setting the Report.ReportSection property.

    It has a sub-property called ReportSubsections , which specifies a reference to the ReportSections object, which is a collection that contains a list of child ReportSection objects to the current object. Looking at this object, it's a list of items that you can index through to get each.

  • How to programmatically change the limit values

    Hi all!

    I would like to create a special tool to automatically update the test sertain limits in a file of sequence of the external file.

    I learned TS API and I got Posibility to build trees for levels of sequence and to get a type of step.

    And I found only the possibility to change the limits of the stage in the dialogue window, interactively.

    But I want to change boundaries programmatically without using interactive mode.

    Is there this possibility in the architecture of the API, TestStand?

    Thank you for the information.

    Now I understand how to access the properties of the step of the TS API.

    I use the "AsPropertyObject" method to pass the search string in step and have asked the value of the property.

    I hope it will be enough to solve my task.

    Thank you very much for the support.

  • How to access the data in the row (text of children) in a pragmatic control tree?

    In LabVIEW 2010, I entered the data in row a tree with pragmatism control using the Add item and providing the child text table and the child tag for the line. When a row in the tree control is selected, I can get the line label in the Value property of the tree. But how do I access the data in the child text table when the line is selected? I can't seem to find a tree control property or method which will return data back.

    What I'm trying to do is: once a line in a tree is selected and a button is pressed, if the line tag is valid, I want to transfer all the data in row in another tree the same formatting. For this I need the data for the tree line and the line that was selected. I don't find a way to get access to these data of the line when it was composed in the tree.

    Can someone tell me how to access pragmatically the child text or row data in a tree control from a selected line in the tree? I have the label of the line, but how do I access data?

    Thank you for your help.

    Looking through numerous examples, I found how to do this using the properties ActiveItemRow and ActiveColNum, but I can't find these documented properties anywhere using LabVIEW. Even research through aid could not do anything about them.

    Where these important parameters are documented?

    Why they do not appear in the help?

    Are there other ways to access the data in the row (child text) form a selected line in a tree control?

  • How to access the sbRIO DIO pin

    Hello

    How to access the pin the sbRIO DIO.

    I enclose the code. According to the code of the indicator DIO2 is supposed to blink, but it is not happenning. Can someone please review the issue and let me know (ASAP) where I was wrong?

    P.S Its URGENT!

    Your FPGA code is more complex that it should be.  Something like this will do what you want.

    Now your RT code... You are simply flashing the fater LED that you can see.  While some expected between your output setting.  I would also use a shift register to store the current value and then just reverse.  In this way, that you have only 1 entry per loop.

Maybe you are looking for