Automatic generation of enum members from name Strings

I have a program in which I read information about Target objects from a text file. I store some of this information as an enum property of the target.
}else if (itemKey.equalsIgnoreCase( "type")) {
currentTarget.descriptor= itemValue;
currentTarget.type = Target.getTargetType(currentTarget.descriptor);And elsewhere in the program I do the file reading and assignment of instance variables:
class Target{
enum TargetType {COUGH_DROP, RICE_CRACKER, PEPTO_BISMOL,UNDETERMINED};
String descriptor;
TargetType type;
returns the target' s type as specified by a descriptor
public static TargetType getTargetType (String descriptorString) {
if (descriptorString.equals( "rice cracker")) {
return (TargetType.RICE_CRACKER);
} else if (descriptorString.equals ("cough drop")){
return (TargetType.COUGH_DROP);
} else if (descriptorString.equals ("Pepto-Bismol")){
return (TargetType.PEPTO_BISMOL);
} else {
return (TargetType.UNDETERMINED);
} I would like to be able to automatically generate the members of the TargetType enum from a list of strings as opposed to needing a method such as getTargetType above. Is this possible?
Regards,
Joe
PS: I completely apologize for the appearance of the code above. I have no idea why this editor removed my indentation and added HTML markers. (I copied the code from a text editor, pasted into this editor, selected the code sections and clicked on the code button )
PPS I now see that after a couple of switches between preview and rich text in the HTML markers have disappeared. WTF?

I'm very curious to understand why one would like to create enum constants at run time? How can therse enums be used in the code that is not created at runtime? What are you really trying to achieve
I know you marked your question as answered, but... you may have a look at the code below. It is a very very simple example of how to map real life descriptions (at runtime) to pre-existing enums. I didn't test it, but for all I know it should just work. Does this solve the problem that you are experiencing?
import java.util.HashSet;
import java.util.Set;
public enum TargetType {
    RICE_CRACKER("C:/Descriptions/RiceCrackers.txt"),
    COUGH_DROP("C:/Descriptions/CouphDrops.txt"),
    PEPTO_BISMOL("C:/Descriptions/PeptoBismol.txt"),
    UNDETERMINED("C:/Descriptions/Empty.txt"),
    public static TargetType getType(String description) {
     for (TargetType targetType : TargetType.values()) {
         if (targetType.contains(description)) {
          return targetType;
     return UNDETERMINED;
    private final String fileName;
    private Set<String> descriptions = null;
    private TargetType(String fileName) {
     this.fileName = fileName;
    private boolean contains(String description) {
     if (descriptions == null) {
         descriptions = new HashSet<String>();
          * Populate descriptions from fileName.
     return descriptions.contains(description);
}Piet

Similar Messages

  • Accessing enum members from enum Class literal

    I'm using enums to provide a configuration framework. They work well, but I've hit a problem. This may be a bad use-case or just end up as a limitation of the enum support.
    In a nutshell I want to return the enum container type from a method and allow clients to access the members of that enum directly. For example:
    interface Widget
      Class<?> getColours();
    class MyWidget implements Widget
      enum COLOUR { RED, GREEN, BLUE };
      public Class<COLOUR> getColours() { return COLOUR.class;}
    // client
    MyWidget w = new MyWidget();
    w.setColour( w.getColours().BLUE ); // compile error!Of course, this gives a compile error as getColours() returned a class literal which doesn't have the field BLUE. However it seems like there should be a way to do this as all the information is there (the class literal has the necessary type information and can see the type is an enum). I've see Class#getEnumConstants() but this defeats the point by using an id or key to the enum rather than the enum member. Perhaps something like Class#asEnum():
    COLOUR b = w.getColours().asEnum().BLUE;I currently solve this by using naming conventions. Each widget implementer is required (by the framework) to provide an enum with the name 'COLOUR' that provides the colours it supports. However I'd prefer to have this on the interface to remind implementers to expose these configuration options.
    One other workaround is to create a custom container that holds a reference to each enum field ... but its not pretty:
    class MyWidget implements Widget
      public static class COLOURS
        private static COLOURS instance = new COLOURS();
        private COLOURS() {}
        public COLOUR RED = COLOR.RED;
        public COLOUR BLUE = COLOR.BLUE;   
        public COLOUR GREE = COLOR.GREEN;
        enum COLOUR { RED, GREEN, BLUE };
      public COLOURS getColours() { return COLOURS.instance;}
    // client
    MyWidget w = new MyWidget();
    w.setColour( w.getColours().BLUE ); // OKHas anyone hit this before and found a better solution? Is there something I've missed? If not does this seem like a reasonable request for improvement?

    I suspect you're better off using the static values() or valueOf(String) methods on the enum you create.
    So you could do
    Colour c = Colour.valueOf("BLUE");or even
    Color particularColour = null;
    for(Colour c : Colour.values()) {
        if (c.isApplicable(someCriteria)) {
            particularColour = c;
            break;
    }assuming you created a method isApplicable in the Colour enum. All I'm trying to suggest in this latter example is that selection of an enum value might be better delegated to the enum than performed by the caller.

  • Automatic generation of PDF file from briefing book in OBIEE11g

    Hi all,
    Could anyone tell me if exist a way to generate PDF files from briefing books automatically in OBIEE11g?
    Thanks
    Annalisa

    I only got so far when I tried to do this in Windows. The problem comes when you try to tell the printer to print to a file with a particular name.
    The first steps are to get GhostWriter for Windows.
    Then you install the Apple LaserWriter pro 600 driver which can print to a postscript file (try it manually first). GhostWriter can then, with a command line command, using a java Process, convert that to a .pdf file.

  • Automatic generation of JSP Project from tables

    JDeveloper had a feature in earlier versions (probably 9i) that automatically creates a JSP/Struts based project that can Add/Edit/Delete from a database table. I couldn't find it in the JDeveloper 10.1.3. Has this feature been taken out or its my inablility to find it?
    Can anyone point me to the right direction?

    We took this off since it was mostly nice for demos but when you wanted to customize the application it wasn't really helpful.
    Go through some of the ADF Tutorials on the JDeveloper tutorial page and you'll see similar functionality done with drag and drop - but in a way that lets you configure and customize whatever you want.

  • Automatic generation of ABAP-classes from Function Groups?

    Hey there,
    is there a way of having (SE24)-ABAP-Classes generatetd outomaticaly by providing an existing function group?
    I think, the following mapping shold be possible::
    - the function group is the class
    - its function modules are public (static) methods
    - any form-routines are private methods
    -> I don't want to to that boring work myself, some tool should be able to do that just fine, right? So, is there such a tool?
    Thanks, regards
    Joachim

    Sorry, sounds like the only two people who answered are not aware of such a tool...
    There is one additional point, which I hadn't thought about initially. With ABAP OO you also have a much stricter syntax and many more statement variants that are obsolete and thus cannot be used. This is another hindrance for writing such a tool (but of course not impossible, I just kind of doubt that any reasonable programmer would write such a thing).
    Anyhow, I never understood why SAP is pushing OO so much (declaring all non-OO as obsolete), even going as far as implementing stricter syntax checks for OO. In my opinion a much better option would've been to implement some flag that switches on the more strict syntax checks, similarly to the Unicode check they've introduced. Coding in OO or non-OO, both have its use. Rules from SAP to code everything in OO even in cases where OO doesn't work seems straight silly as a general recommendation: E.g. if I have to code an RFC module, why would I want to bloat my code by introducing a class for implementing the functionality so that the RFC is just a wrapper around the class (unless the additional class gives me some real benefit)?
    As much as I appreciate using OO classes supplied by SAP, I often have difficulties seeing objects in the requirements that I have to code (which might of course just be a reflection of my programming skills). A class with just some static methods is often an indication of poor OO design, i.e. there is no reasonable/tangible object and all you have is a utility class with a collection of various methods. To me it's important that the code is well structured, doesn't have any side effects, etc. This can be achieved with non-OO coding as well as OO, but switching from non-OO to OO doesn't guarantee at all that the code is any better.
    In the end, if you just have a single function group, I'd recommend to do the translation manually and try to apply good OO design principles (instead of a straightforward 1-to-1 translation). E.g. for a class with just static methods (which I'd expect an automated translation would result in) one might want to take a peek at [singletons are evil|http://www.c2.com/cgi/wiki?SingletonsAreEvil] versus [singletons are good|http://www.c2.com/cgi/wiki?SingletonsAreGood]. I know it's silly advice if you're a seasoned OO programmer; but if not, I think your time is much better spent by thinking about the design and then applying it instead of using some automated tools where you'd later have to anyhow do some refactoring...

  • Automatic Generation of Reservation Document from Sales Order

    Hello ABAP Peeps,
    I require some assistance. I need to have a resevation document to be created and saved automatically as soon as the Sales Order is saved. What sort of setting would I need to make for this to take place?
    Many Thanks
    Pranzo

    is an Abap forum, better ask in forums like or look via SPRO at the area Sales and Distribution, Sales, Sales Documents, Schedule Lines, Define Schedule Line Categories (VOV6).
    Regards,
    Raymond

  • Question on automatic generation of PO's through ME59 ??

    hi all,
    while automatic generation of PO's from Pr's through me59n i need to check if the PR has OA ( outline agrement ) or contract assigned to it. if only OA or contract is assigned to PR then PO needs to be generated else PO should not be generated.
    to summerize for PR's which does not have contract assigend to it. it should not generate PO's how do i restrict . please let me know.
    Thanks,
    Shiva..
    Edited by: Alvaro Tejada Galindo on Mar 4, 2008 2:44 PM

    Hi,
    For automatic PO creation check the following steps.
    1) Material Master purchasing view tick automatic PO check box
    2) Vendor Master purchasing view tick automatic PO check box.
    3) Maintain Source list for Vendor & Material.
    4) Maintain Purchase Info Record.
    5) Create a Purchase Requisition.
    6) Use T.Code: ME59N & execute for PR for vendor, you will be able to create automatic PO.
    Note:
    1.Ensure that Purchase Info Record should be there.
    2.If you have more than one vendor then fixes only one vendor in source list.
    3.During PR creation select the check box of Source Determination
    Regards,
    Biju K

  • Can you remove members from the outline using ESSCMD?

    The product line dimension in my cube looks something like this:Product Line Product 1 Product 2 Service Parts Part 1 Part 2 etc.I have an automated script which builds the product line dimension, loads a new data set, and does a CALC ALL to roll up Part 1, Part 2, etc., into Service Parts. Once that rollup has occurred, I want to remove Part 1, Part 2, etc., from the outline, but I have not found a way to do that from ESSCMD. Is there a way I can automate the removal of members from a dimension?Any hints or suggestions are greatly appreciated.-jimb

    You could create a new dimension build file for your products dimension but only down to the service parts level. then use a load rule with the remove unspecified box checked on the Dimension build setting tab. This shold cause a restructure of the database, hopefully your product dimension is sparse.Good LuckGlenn UrbanDirector of consultingVision BIA, LLC630.873.3165

  • Setting the name of a new object from a string

    Is there anyway I can set the object name of a newly created
    object from a string?
    eg.
    (the code below generates a compile time error on the
    variable declaration)
    public function addText(newTxt:String, txt:String,
    format:TextFormat):void {
    var
    this[newTxt]:TextField = new TextField();
    this[newTxt].autoSize = TextFieldAutoSize.LEFT;
    this[newTxt].background = true;
    this[newTxt].border = true;
    this[newTxt].defaultTextFormat = format;
    this[newTxt].text = txt;
    addChild(this[newTxt]);
    called using>
    addText("mytxt", "test text", format);
    I could then reference the object later on without using
    array notation using mytxt.border = false; for example
    There are many a time when I want to set the name of a new
    object from a string.
    In this example I have a function that adds a new text object
    to a sprite.
    The problem is, if I call the function more than once then
    two textfield objects will exist, both with the same name. (either
    that or the old one will be overwritten).
    I need a way of setting the name of the textfield object from
    a string.
    using
    var this[newTxt]:TextField = new TextField()
    does not work, If I take the "var" keyword away it thinks it
    a property of the class not an object.
    resulting in >
    ReferenceError: Error #1056: Cannot create property newTxt on
    Box.
    There must be a way somehow to declare a variable that has
    the name that it will take represented in a string.
    Any help would be most welcome
    Thanks

    Using:
    var this[newTxt]:TextField = new TextField()
    is the right approach.
    You can either incrment an instance variable so that the name
    is unique:
    newTxt = "MyName" + _globalCounter;
    var this[newTxt]:TextField = new TextField();
    globalCounter ++;
    Or store the references in an array:
    _globalArray.push(new TextField());
    Tracy

  • Automatic Generation of classes with required attribute names

    Hi ,
    I am new to XML technologies ...I am having a problem in deciding whether I
    should use JAXB or Castor for data binding.
    The problem is the attributes I am to use are named differently as that found in
    the DTD.I have creted my own classes using the required attribute names and the
    n mapped them using the Castor mapping with the attributes.
    I was wondering how should I achieve --"automatic generation of classes" with th
    e specified attribute names?
    I understand that JAXB can be used to automatically generate classes ,but this
    uses the same default names as that of the XML file ..is there a way of forcing
    JAXB to generate classes that use my name attributes rather than that of the XM
    L dtd
    If I use Castor ..is there a way to do the same.Generate Classes with the specif
    id attributes

    Hi ,
    I am new to XML technologies ...I am having a problem in deciding whether I
    should use JAXB or Castor for data binding.
    The problem is the attributes I am to use are named differently as that found in
    the DTD.I have creted my own classes using the required attribute names and the
    n mapped them using the Castor mapping with the attributes.
    I was wondering how should I achieve --"automatic generation of classes" with th
    e specified attribute names?
    I understand that JAXB can be used to automatically generate classes ,but this
    uses the same default names as that of the XML file ..is there a way of forcing
    JAXB to generate classes that use my name attributes rather than that of the XM
    L dtd
    If I use Castor ..is there a way to do the same.Generate Classes with the specif
    id attributes

  • Dynamic Variable name (for int/long) from a String variable

    Hi,
    I want to give a int/long variable name from a String.
    for ex.
    String str = lookup + "Id";
    lookup is a String variable coming from XML. Now, for instance lookup="name". So str = "nameId".
    Now I want to create a int/long variable by nameId.
    Could anybody tell me the way how to do. Please don't tell to use MAP.
    Edited by: Shah on Dec 5, 2007 3:26 PM

    Well you can't. Use a Map.
    The compiler translates variable names into slot numbers, either within an object or withing the local "stack frame" and these slot numbers are assigned names at compile time. No new slots can be created at run time. Java is not Basic.
    Reflection allows you to find existing field names and methods (not local variables), so it's possible to map, for example, XML attribute names to field names or setters in an object but the names have to be known at compile time.

  • How to get the number of community members from outside the community

    Hi everyone.
    I need to know if there is any way to get the number of community members from outside the community, I mean, not using the "What's happening" webpart. I want to build up a page with a Webpart that summarize my three most visited communities indicating
    number of members, three last messages in the newsfeed, and number of posts in blog, wikis, document libraries, etc.
    Do I need statistics to get this kind of information? Should I use Sharepoint Object model instead?
    Here is an example of what I need:
    - Community name
    - Number of members
    - Community activity (messages, docs uploaded to library, etc)
    - Number of posts in calendar, blog, wiki that belongs to community
    Thank you all!

    Hi Thuan.
    Thanks for your answer but it does not help me because these communities are Sharepoint Communities not external sites so I need to get that information using SP object model and BCS in this case is useless.
    EDIT
    I found the solution using the search objects but I was only able to get members, discussions and replies
    using (ClientContext clientContext = new ClientContext("URL_OF_ENTERPRISE_SEARCH_CENTER"))
    KeywordQuery keywordQuery = new KeywordQuery(clientContext);
    keywordQuery.QueryText = "The_Name_of_the_Community WebTemplate:COMMUNITY";
    SearchExecutor searchExecutor = new SearchExecutor(clientContext);
    ClientResult<ResultTableCollection> results = searchExecutor.ExecuteQuery(keywordQuery);
    clientContext.ExecuteQuery();
    System.Collections.Generic.IDictionary<string, object> ret = null;
    foreach (System.Collections.Generic.Dictionary<string, object> resultRow in results.Value[0].ResultRows)
    Console.WriteLine("{0}: {1} ({2})", resultRow["CommunityMembersCount"], resultRow["CommunityTopicsCount"], resultRow["CommunitiyRepliesCount"]);
    This is a Console Application.
    I hope someone helps

  • Get a variable by a name string? how

    Hi,
    I am currently developing an interpreter which is of cause a class.
    This interpreter will be initiated with several pieces of strings mixed
    with unknown number of variables with some order which is unknown previously.
    So the better way is just passing one string which contains the variable
    name strings and return a collection of variables specified by the variable
    ames contained in this string.
    Problem is:
    How can I get a variable from a name string, instead of a name
         variable?
         Java Reflection can only return fields, but not variables
         Any idea?
         And how JNI could do perphaps?
    Any help appreciated
    Thanks in adv
    dunson

    As far as i know, the names of local variables, that are only used inside methods, are not preserved in the bytecode. That means you can't grab from them by name, whatever you do. You are able to grab members though, through reflection, but it's not very efficient. I wouldn't recommend it.
    As suggested, I think you need to make special provision for this with a structure like a Hashtable. It's better programming practice, it's more efficient, and you'll find it much easier to program.
    Something like this:
    import java.util.*;
    class Doodad {
      Map stuff = new HashMap();
      Object getValue(String code) {
        return stuff.get(code);
      void setValue(String code, Object value) {
        stuff.put(code, value);

  • Problems with Reflection API and intantiating an class from a string value

    I want to instantiate a class with the name from a String. I have used the reflection api so:
    static Object createObject(String className) {
    Object object = null;
    try {
    Class classDefinition = Class.forName(className);
    object = classDefinition.newInstance();
    } catch (InstantiationException e) {
    System.out.println(e);
    } catch (IllegalAccessException e) {
    System.out.println(e);
    } catch (ClassNotFoundException e) {
    System.out.println(e);
    return object;
    Let's say my class name is "Frame1".
    and then if i use:
    Frame1 frm = (Frame1) createObject("Frame1");
    everything is ok but i cannot do this because the name "Frame1" is a String variable called "name" and it doesn't work like:
    name frm = (name) createObject("Frame1");
    where i'm i mistaking?
    Thanks very much!

    i have understood what you have told me but here is a little problem
    here is how my test code looks like
    Class[] parameterTypes = new Class[] {String.class};
    Object frm = createObject("Frame1");
    Class cls = frm.getClass();
    cls.getMethod("pack",parameterTypes);
    cls.getMethod("validate",parameterTypes);
    everything works ok till now.
    usually if i would of had instantiated the "Frame1" class standardly the "cls" (or "frm" in the first question ) object would be an java.awt.Window object so now i can't use the function (proprietary):
    frame_pos_size.frame_pos_size(frm,true);
    this function requires as parameters: frame_pos_size(java.awt.Window, boolean)
    because my cls or frm objects are not java.awt.Window i really don't find any solution for my problem. I hope you have understood my problem. Please help. Thanks a lot in advance.

  • How do I use the event.target.name String with an external dispatchEvent?

    ...I hope the title question makes sense...
    On my stage I have an externally loaded SWF with a button. When clicked the button dispatches an event to the main stage.
    On the main stage a listener then loads an SWF into a loader called gallery.
    The gallery loader is also being shared by buttons on the main stage which use the event.target.name String to call in SWFs with corresponding names.
    I am using Tweens to fade-out and -in content to the gallery when a button is pressed.
    Loading the SWFs was working until I tried to create a universal button function for the dispatchEvent buttons...
    The problem I have is that I don't know how to define the String to tell the newSWFRequest where to find the SWF when triggered by the external buttons.
    (I may be doing this all wrong... but figured the best way to load an SWF on to the main stage from an external SWF was by using dispatchEvent??)
    My code triggers the Event and the gallery loader fades out, but then it cannot find the new SWF:
    Error #2044: Unhandled IOErrorEvent:. text=Error #2035: URL Not Found.
    Please can someone help me understand the way to make the String point in the right direction? (I think the only errors are in bold below)
    Code:
    var myTweenIn2:Tween;
    var myTweenOut2:Tween;
    var nextLoadS2:String;
    // Listen for external event dispatched from external btns
    addEventListener("contactStage", btnClickExtrnl);
    function btnClickExtrnl(e:Event):void {
    nextLoadS2 = ?????
    myTweenOut2=new Tween(gallery,"alpha",None.easeOut,gallery.alpha,0,0.2,true);
    myTweenOut2.addEventListener(TweenEvent.MOTION_FINISH,tweenOutCompleteF2);
    // Btns Universal function
    function tweenOutCompleteF2(e:TweenEvent){
    myTweenOut2.removeEventListener(TweenEvent.MOTION_FINISH,tweenOutCompleteF2);
    myTweenOut2=null;
        var newSWFRequest:URLRequest = new URLRequest("swfs/" + nextLoadS2 + ".swf");
    myTweenIn2 = new Tween(gallery, "alpha", None.easeOut, gallery.alpha, 1, 0.2, true);
        gallery.load(newSWFRequest);
        gallery.x = Xpos;
        gallery.y = Ypos;
    Thank you.

    That works – thank you!
    I'm now using this code to fade in each of the SWFs:
    function contactStage(e:MouseEvent):void {
        var newSWFRequest:URLRequest = new URLRequest("swfs/"+e.currentTarget.name+".swf");
        myTweenIn = new Tween(gallery,  "alpha", None.easeOut, 0, 1, 0.2, true);
        gallery.load(newSWFRequest);
        gallery.x = Xpos;
        gallery.y = Ypos;
    But I cannot add the fade out function. I have amended the above code to create:
    var myTweenOutX:Tween;
    var myTweenInX:Tween;
    function contactStage(e:MouseEvent):void {
    myTweenOutX=new Tween(gallery,"alpha",None.easeOut,gallery.alpha,0,0.2,true);
    myTweenOutX.addEventListener(TweenEvent.MOTION_FINISH,tweenOutCompleteFX);
    function tweenOutCompleteFX(e:TweenEvent){
    myTweenOutX.removeEventListener(TweenEvent.MOTION_FINISH,tweenOutCompleteFX);
    myTweenOutX=null;
        var newSWFRequest:URLRequest = new URLRequest("swfs/"+e.currentTarget.name+".swf");
    myTweenInX = new Tween(gallery,  "alpha", None.easeOut, 0, 1, 0.2, true);
        gallery.load(newSWFRequest);
        gallery.x = Xpos;
        gallery.y = Ypos;
    But get this error:
    ReferenceError: Error #1069: Property name not found on fl.transitions.Tween and there is no default value.
    at ACOUSTIC_fla::MainTimeline/tweenOutCompleteFX()[ACOUSTIC_fla.MainTimeline::frame1:110]
    at flash.events::EventDispatcher/dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at fl.transitions::Tween/set time()
    at fl.transitions::Tween/nextFrame()
    at fl.transitions::Tween/onEnterFrame()
    Where am I going wrong?

Maybe you are looking for