Passing any enum type to a method

Consider I have created some enums:
public enum Day {
    SUN, MON, TUE, WED, THU, FRI, SAT
public enum Month {
    JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC
}I want to create a method that will accept any type of enum and display all values. So the call would look something like:
showAll(Day);
showAll(Month);I'm not sure what to pass to the method. My understanding of Generics is rudimentary at best, despite reading the tutorial several times now. Here is some uncompilable code that might illustrate:
public void showAll(EnumType enumType)  // <--- not sure what to pass here
  Enum[] allValues = enumType.values();
  // then, loop over the allValues array and I can proceed from here
}The actual code is needed is for displaying a list of checkboxes to the user where the input is the enum class, and the checkboxes are every enum value.

brucechapman wrote:
You could use this signature
<T extends Enum<T>> void showall(Class<T> clazz); Then use reflection to invoke the values() method which you know is there because only Class objects for enums can be passed in.I'll be honest, that signature looks very strange to me. However, I tried it anyway and it worked even without reflection.
public class PassingEnums
  public enum Day {
    SUN, MON, TUE, WED, THU, FRI, SAT
  public enum Month {
    JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC
  public <T extends Enum<T>> void showAll(Class<T> clazz)
    T[] types = clazz.getEnumConstants();
    for (int i = 0; i < types.length; i++)
      System.out.println(types.toString());
public static void main(String[] args)
PassingEnums test = new PassingEnums();
test.showAll(Day.class);
System.out.println("---");
test.showAll(Month.class);
}Or were you thinking of something else?
I guess I'll have to hit the tutorials again, since that signature looks foreign to me.
Thanks.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Similar Messages

  • Passing enums to functions without knowing the specific enum type

    My application needs the function invocation feature by using reflection mechanism. The function parameters are restricted to string, int, float and enums. I am facing problems with enums.
    Is there a way to invoke the function by passing specific enum type as parameter to the function.
    For eg:
    public void doProcess(int i, COLOR.RED){
    I should be able to invoke the above function using reflections. How dynamic casting to COLOR can be done is the question here?

    The application takes XML file as an input. This file has processing instructions. The processing instruction provides data about the class name, function name and parameters specifications like
    Classname_FunctionName("String param", 123, COLOR.RED)
    The application should invoke the corresponding library function by passing these parameters after assessing the correct types.

  • How to pass any type of objects into Portal's rules engine?

    Is that possible to pass any type of objects into Portal's rules engine? Or BEA's Portal service rules engine can only allow to pass a limited number of objects?
    Are there any information about BEA's rules engine? and Can we use its rules engine without using its Portal service?
    Thank you.

    I worked on BEA rules engine 4 months back. I'm sure you can pass any JAVA object to it's working meomory. I am giving my sample rules here, hope it will be helpful for you.
    I just replace pcakage name, other than that everything is from wroking project. Open in xml spy, it should be clear from the desc. If you have any questions post back.
    <cr:rule-set is-complete="true" xmlns="http://www.bea.com/servers/p13n/xsd/expression/expressions/2.1.1" xmlns:cr="http://www.bea.com/servers/p13n/xsd/rules/core/2.1.1" xmlns:literal="http://www.bea.com/servers/p13n/xsd/expression/literal/1.0.1" xmlns:string="http://www.bea.com/servers/p13n/xsd/expression/string/1.0.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bea.com/servers/p13n/xsd/rules/core/2.1.1 rules-core-2_1_1.xsd">
         <cr:rule is-complete="true">
              <cr:name>TaxForm1040</cr:name>
              <cr:description>If salary is 70,000 then this rule makes 1040 as required form</cr:description>
              <cr:conditions>
                   <multi-and>
                        <multi-and>
                             <equal-to>
    <instance-method>
    <variable>
    <name>SalaryField</name>
    <type-alias>com.blah.field.REInputObject</type-alias>
    </variable>
    <name>getKey</name>
    </instance-method>
    <literal:string>Salary</literal:string>
    </equal-to>
    <equal-to>
    <instance-method>
    <variable>
    <name>SalaryField</name>
    <type-alias>com.blah.field.REInputObject</type-alias>
    </variable>
    <name>getValue</name>
    </instance-method>
    <literal:integer>70000</literal:integer>
    </equal-to>
                        </multi-and>
                   </multi-and>
              </cr:conditions>
              <cr:actions>
                   <new-instance>
                        <type-alias>com.blah.field.RequiredField</type-alias>
                        <arguments>
                             <literal:string>1040</literal:string>
                        </arguments>
                   </new-instance>
              </cr:actions>
         </cr:rule>
    </cr:rule-set>

  • Query on conversion between String to Enum type

    Hi All,
    I would like to get advice on how to convert between char and Enum type. Below is an example of generating unique random alphabet letters before converting them back to their corresponding letters that belonged to enum type called definition.Alphabet, which is part of a global project used by other applications:
    package definition;
    public enum Alphabet
    A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S,
    T, U, V, W, X, Y, Z
    public StringBuffer uniqueRandomAlphabet()
    String currentAlphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    StringBuffer randomAlphabetSB = new StringBuffer();
    for (int numberOfAlphabet=26; numberOfAlphabet>0; numberOfAlphabet--)
    int character=(int)(Math.random()* numberOfAlphabet);
    String characterPicked = currentAlphabet.substring(character, character+1);
    // System.out.println(characterPicked);
    randomAlphabetSB.append(characterPicked);
    StringBuffer remainingAlphabet = new StringBuffer( currentAlphabet.length() );
    remainingAlphabet.setLength( currentAlphabet.length() );
    int current = 0;
    for (int currentAlphabetIndex = 0; currentAlphabetIndex < currentAlphabet.length(); currentAlphabetIndex++)
    char cur = currentAlphabet.charAt(currentAlphabetIndex);
    if (cur != characterPicked.charAt(0))
    remainingAlphabet.setCharAt( current++, cur );
    currentAlphabet = remainingAlphabet.toString();
    return randomAlphabetSB;
    // System.out.println(randomAlphabetSB);
    I got the following compilation error when trying to pass (Alphabet) StringBuffer[0] to a method that expects Alphabet.A type:
    inconvertible types
    required: definition.Alphabet
    found: char
    Any ideas on how to get around this. An alternative solution is to have a huge switch statement to assemble Alphabet type into an ArrayList<Alphabet>() but wondering whether there is a more shorter direct conversion path.
    I am using JDK1.6.0_17, Netbeans 6.7 on Windows XP.
    Thanks a lot,
    Jack

    I would like to get advice on how to convert between char and Enum type. Below is an example of generating unique random alphabet lettersIf I understand well, you may be interested in method shuffle(...) in class java.util.Collections, which randomly reorders a list.
    before converting them back to their corresponding letters that belonged to enum type called definition.AlphabetIf I understand well, you may be interested in the built-in method Alphabet.valueOf(...) which will return the appropriate instance by name (you'll probably have no problem to build a valid String name from a lowercase char).

  • Enum type class hierarchy.

    Hi,
    I was reviewing and eagerly testing the Typesafe Enum Facility (enum types) on 1.5.0 beta, which is still in Public Review in the JCP (JSR-201).
    I would would like to mention a missing feature that I find usefull and powerfull for a custom framework architecture.
    I understand and agree with respect to the first question on the JSR 201 FAQ, about subclassing enums.
    Having enumeration constants from both the superclass and the subclass is quite confusing and I agree with disallowing it from the language.
    But I miss the ability to inherit custom behavior (methods, and not enumeration constants), for an enum type, from a middle superclass. This middle superclass could be a base class for enum types within a specific development framework (and of course, java.lang.Enum would by in is class hierachy).
    The actual proposal allows for an enum type to only have java.lang.Enum as superclass, from which it inherits methods like name() and ordinal(). But in a proyect where a large number of diferent enum types with a common and custom extra framework behavior (like a localizedName() or propertyKey() method for example) would need the implementation of this behavior in each enum type source code (or in a helper class).
    Following the example above, the actual proposal would need the following coding in order to add an additional behavior to all (or some) of the enum types in a development proyect:
    public interface MyBaseFrameworkEnum {
         String localizedName();
         String propertyKey();
    public enum FooEnum implements MyBaseFrameworkEnum {
         FOO_A, FOO_B;
         public String localizedName() {
              //..... coding necesary in every enum implementing BaseFrameworkEnum
         public String propertyKey() {
              //..... coding necesary in every enum implementing BaseFrameworkEnum
    As you see, every enum type in my example framework (like FooEnum) would need to code both methods localizedName() and propertyKey() which would produce a lack of centralized code and increase of class file size.
    It would be very powerfull to be able to use the following coding:
    public abstract enum MyBaseFrameworkEnum {
         public String localizedName() {
              //..... coding centralized
         public String propertyKey() {
              //..... coding centralized
    public enum FooEnum extends MyBaseFrameworkEnum {
         FOO_A, FOO_B;
    As you see, with this abstract enum MyBaseFrameworkEnum (which does not falls in the subclassing problem mentioned in the FAQ) does not define enum constants and will pass its custom behavior to its subclass enums. thus centralizing the related code.
    I generally use an implementation of the Typesafe Enum Pattern so I really am looking forward for this new Typesafe Enum Facility in the Java language. But, as an example, I generally use common features in my enums, a properyKey() method used to get a unique key in order to internationalize my applications, since a description to enums is normally needed to be displayed to users.
    I believe this capability would be very powerfull in cases where common features are needed for enums in a development proyect with respect of:
    - code centralization and maintainance.
    - class file size.
    - source code readability.
    This extension would not contradict the actual definition, it would only allow for an enum type to be able to extend from another abstract enum type which has no enumeration constants.
    I believe that if there are other programmers that find this extension worth, it could make it in the JSR-201(which is in public review until February 21th) process before the final specification.
    Regards,
    Luis Longeri

    It would be very powerfull to be able to use the
    following coding:
    public abstract enum MyBaseFrameworkEnum {
         public String localizedName() {
              //..... coding centralized
         public String propertyKey() {
              //..... coding centralized
    public enum FooEnum extends MyBaseFrameworkEnum {
         FOO_A, FOO_B;
    }Luis, I like your idea but don't really like the idea of an abstract enum. I think this would be better
    public class MyBaseFrameworkEnum extends Enum {
         public String localizedName() {
              //..... coding centralized
         public String propertyKey() {
              //..... coding centralized
    public enum FooEnum extends MyBaseFrameworkEnum {
         FOO_A, FOO_B;
    }However, this always opens up the risk of you breaking the enum specific stuff, so all the vulnerable Enum methods would need to be declared "final".
    Because you are unlikely to see this in the language any time soon (if at all), you can always centralise your code in some static methods that take the enum as an argument
    public class MyBaseFrameworkEnumTools {
         public String localizedName(Enum e) {
              //..... coding centralized
         public String propertyKey(Enum e) {
              //..... coding centralized

  • Passing values from HTML to JSP method,

    Hello:
    I am starting to wonder if what I am doing will ever work...
    Ok, I am trying to avoid javascript. I have a drop-down list named "year" and I wish to call a JSP method that is defined/declared in the same JSP.
    First, I want to pass the chosen option to the method and then store the name/value in a global variable.
    Second, depending on what the user selects, I will get values from an array defined/initialized on page load AND display those values in another drop-down list.
    As a test, and until now, I have done this. I am not passing anything yet, I just wanted to test this "fuzzy logic" I am having:
    <%!
    String currentYear;
    private void showDaysInDDList()
    currentYear = request.getparameter("year");
    %>
    Then on the HTML part of the page I have a drop-down list:
    <html>
    <head>
    <title></title>
    <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <body bgcolor="ffffcc">
    <form method="POST" name="form1" action="left.jsp">
    <select name="year" onchange="<%=showDaysInDDList()%>">
         <option></option>
         </select>
    I am getting the following errors:
    An error occurred at line: 105 in the jsp file: /p1/left.jsp
    request cannot be resolved
    ....and regarding to the onchange="<%=showDaysInDDList()%>"> part I am getting the following:
    An error occurred at line: 204 in the jsp file: /p1/left.jsp
    The method print(boolean) in the type JspWriter is not applicable for the arguments (void)
    In the action="left.jsp", left.jsp is the same page where the drop-down list and the method is. I am not sure if that is another error.
    I will continue here with my coffee ... any help will be extremely appreciated !!..
    I'll have to shut down my "asp.net mind" for a while..
    I'll reply later,
    MMS

    Ok, this is a bit messy here. I don't know how much you've read up on JSP but you seem confused about some fundamentals to me. However, you mention that you've worked with ASP .net so I'm going to assume you do have some notion of how thing should work in general.
    1. JSP is on the server-side and events like onchange that you've used take place on the client-side after the JSP/ servlet code has run and produced the HTML page. So calling your showDaysInDDList() will not work.
    2. Are you sure you know how the declaration tags ( <%! %> ) work? When you normally write JSP code without these tags, all that code gets compiled into the service method of the corresponding servlet that the JSP gets turned into. But, you can declare your own methods and variables outside the service method by using these tags.
    So what you're effectively doing is declaring
    private String/ void showDaysInDDList()
    }and followed by your usual _jspService()
    public void _jspService(HttpServletRequest request,
       HttpServletResponse  response)
         throws IOException, ServletException
    }Now it may be clear, that the request object is not available in the showDaysInDDList() method by default; you'll either have to declare it ( not sure if it's good programming practice or not ) or pass the required parameters in the call.
    3. Like you seem to have realized, that error about the printing of booleans was related to the return type of your method because <%= %> translates to out.println(); and since the argument was the method call, the return value was to be printed which here was a void ( not sure why it says boolean though :D ).
    Read up on this introduction to JSPs http://java.sun.com/developer/onlineTraining/JSPIntro/contents.html, seems to be pretty good and covers everything in quick, short chunks.
    Hope this helps.

  • Exporting parameter of type table in Method of a Class

    Hi Experts,
    I want to pass an internal table from my method in ABAP class to a workflow.
    For thi spurpose i have cretaed a parameter of type table in the method.
    My problem is that i am not able to bind this to a workflow/task  container.
    I can see all the other parameters of the method in thw workflow while binding except for the parameter of type table ( i.e internal table ).
    Any idea ?
    Thanks,
    Radhika.

    Assuming that you are trying to export the internal table from class method to task conatiner.
    I have cretaed a Structure 'zemails' in se11
    Already you have created a Structure in the SE11 , why don't you just create one Table Type of ZEMAILS in SE11. Once you hvae created in DDIC then in the class signature declare the ltmails of type the tabale type that you create. and then in the task conatiner also try to declare the container element with the same name and same table type.
    In the class method declare the lt_mails as Exporting. save and actiavte. And one more thing if that element is not present in the Task conatiner then as soon as you try to open in the change mode and click on the binding button of the task it will prompt you asking whether you want to trnasfer the mssing elements if you clcik Yes then the same element which you have declared in the class will created with the same type. but make sure in the task conatiner you delcare the lt_mails as IMport export element.

  • How to pass calculated value to Application Module method?

    I am a newbie to ADF. Ithink I am missing something very basic:
    In JDeveloper 10.1.3.3 using ADF, I am trying to pass the session ID to a method in my App Mod, but the method receives a null value. I think I a getting the session ID too late in the process, but do not know where else to get it.
    Here are the details:
    I am passing 3 argument to a method called ProcessReport:
    public String ProcessReport(Number reportNumber, Double caratWeight, String sessionID)
    In my PageDef I have:
    <p>
    &lt;executables&gt;
    &lt;variableIterator id="variables"&gt;
    &lt;variable Type="oracle.jbo.domain.Number"
    Name="ProcessReport_reportNumber" IsQueriable="false"/&gt;
    &lt;variable Type="java.lang.Double" Name="ProcessReport_caratWeight"
    IsQueriable="false"/&gt;
    &lt;variable Type="java.lang.String" Name="ProcessReport_sessionID"
    IsQueriable="false"/&gt;
    &lt;/variableIterator&gt;
    &lt;/executables&gt;
    &lt;bindings&gt;
    </p>
    <p>
    &lt;methodAction id="ProcessReport" MethodName="ProcessReport"
    RequiresUpdateModel="true" Action="999"
    IsViewObjectMethod="false" DataControl="RC2DataControl"
    InstanceName="RC2DataControl.dataProvider"
    ReturnName="RC2DataControl.methodResults.RC2DataControl_dataProvider_ProcessReport_result"&gt;
    &lt;NamedData NDName="reportNumber" NDType="oracle.jbo.domain.Number"
    NDValue="${bindings.ProcessReport_reportNumber}"/&gt;
    &lt;NamedData NDName="caratWeight" NDType="java.lang.Double"
    NDValue="${bindings.ProcessReport_caratWeight}"/&gt;
    &lt;NamedData NDName="sessionID" NDType="java.lang.String"
    NDValue="${bindings.ProcessReport_sessionID}"/&gt;
    &lt;/methodAction&gt;
    &lt;attributeValues id="reportNumber" IterBinding="variables"&gt;
    &lt;AttrNames&gt;
    &lt;Item Value="ProcessReport_reportNumber"/&gt;
    &lt;/AttrNames&gt;
    &lt;/attributeValues&gt;
    &lt;attributeValues id="caratWeight" IterBinding="variables"&gt;
    &lt;AttrNames&gt;
    &lt;Item Value="ProcessReport_caratWeight"/&gt;
    &lt;/AttrNames&gt;
    &lt;/attributeValues&gt;
    &lt;attributeValues id="sessionID" IterBinding="variables"&gt;
    &lt;AttrNames&gt;
    &lt;Item Value="ProcessReport_sessionID"/&gt;
    &lt;/AttrNames&gt;
    &lt;/attributeValues&gt;
    &lt;/bindings&gt;
    </p>
    On my page I have added an outputText control called sessionID to hold the session ID.
    In my command Button to submit the page I have and action to call a method in my backing bean:
    The code is:
    FacesContext ctx = FacesContext.getCurrentInstance();
    ExternalContext ectx = ctx.getExternalContext();
    HttpSession mySession = (HttpSession) ectx.getSession(false);
    String theSessionID = mySession.getId();
    sessionID.setValue(theSessoinID) // I hope it populates the outputText control and is added to the binding to be passed to the ProcessReport method
    BindingContainer bindings = getBindings();
    OperationBinding operationBinding = bindings.getOperationBinding("ProcessReport");
    Object result = operationBinding.execute();
    if (!operationBinding.getErrors().isEmpty()) {
    return null;
    String resultStr = (String) result;
    return resultStr;
    No luck! I think I should get the sesson ID earlier, when the page loads, but I do not know where to put the code.
    Any suggestions would be appreciated.
    John

    Hi,
    here's what I would do
    1. Create a managed bean as follows
    import javax.faces.context.ExternalContext;
    import javax.faces.context.FacesContext;
    import javax.servlet.http.HttpSession;
    public class HTTPSessionAccessBean {
        public HTTPSessionAccessBean() {
        public void setHttpSessionId(String httpSessionId) {
        public String getHttpSessionId() {
            FacesContext ctx = FacesContext.getCurrentInstance();
            ExternalContext ectx = ctx.getExternalContext();
            HttpSession mySession = (HttpSession) ectx.getSession(false);
            String sessionId = mySession.getId();
            return sessionId;
    }2. In the ApplicationModule Impl class create the following method and expose it as a clientInterface
        public void setSession(String sessionId){
           ((SessionImpl)this.getSession()).getEnvironment().put("http_session",sessionId);
        }3) In the pageDef File create a method binding as
    <methodAction id="setSession"
                      InstanceName="AppModuleDataControl.dataProvider"
                      DataControl="AppModuleDataControl" MethodName="setSession"
                      RequiresUpdateModel="true" Action="999"
                      IsViewObjectMethod="false">
          <NamedData NDName="sessionId"
                     NDValue="${HttpSession.httpSessionId}"
                     NDType="java.lang.String"/>4) In the same pageDef file create an invokeAction
        <invokeAction id="setSessionInAM" Binds="setSession"
                      RefreshCondition="#{!adfFacesContext.postback}"/>The session ID is now accessible from the ApplicationModule as
            Hashtable env = ((SessionImpl)this.getSession()).getEnvironment();
            String sessonId =(String) env.get("session);
            }This maintains the separation of model/view layer
    Frank

  • Why java take enum type off

    why java take enum type off?
    When in switch statement, it become complex without enum type.
    Enum can constrained the range of integer value. Taking enum type off,
    method parameter checking will take lots effort.
    can any way to replace the functions of enum type.

    It was a disputable design decision.
    The original C "enum" type is however somewhat flawy from its lack of encapsulation (its elements "pollute the global namespace" - they are for this purpose!) and would not seamless fit into the typed, OO Java philosophy.
    Otherwise put, the original "C" enum fits well to the C philosophy but no to the C++ or Java one.

  • Passing general "enum" "class" "thing" :-(

    What I'm trying to do is pass a general enum to a method, like this:
    public void parseEnum(enum toParse)
         for(enum blah : enum.values())
              System.out.println(blah);
    }or whatever (don't care if the stuff inside the method works right now, just threw up an example). I can't do this. Why not? Is there some kind of way I can manage to do this?
    The problem is that I have a whole bunch of enums structured like this:
    enum ListOfElementIds
         ID_ONE( "ThingOne" ),
         ID_TWO( "ThingTwo" ),
         ETC( "ThingThreeOhNoes" ),
         AND_ETC( "ThingFourIsTooMany" );
         private String elementId;
         String getElementId()
              return elementId;
         ListOfElementIds( String elementId )
              this.elementId = elementId;
    }and I'd LIKE to, via a single method, cycle through each of the "values" (ID_ONE would be a value) of any enum I give as a parameter of the method.
    If I'm not explaining this well, please let me know how I can elaborate so as to make my problem as lucid as possible :-P
    (I'm a QA tester writing selenium tests and all the developers that I usually bug about this stuff are OoO :-( )

    import java.lang.reflect.*;
    enum ExampleEnum {HELLO, WORLD};
    public class EnumExample {
        public void iterate(Class<? extends Enum> cls) {
            try {
                Method m = cls.getMethod("values");
                Enum[] values = (Enum[]) m.invoke(null);
                for(Enum e : values) {
                    process(e);
            } catch (NoSuchMethodException exc) {
                exc.printStackTrace();
            } catch (IllegalAccessException exc) {
                exc.printStackTrace();
            } catch (InvocationTargetException exc) {
                exc.printStackTrace();
        public void process(Enum e) {
            System.out.println(e);
        public static void main(String[] args) {
            new EnumExample().iterate(ExampleEnum.class);
    }The values method is static.

  • Reflection and enum types: help needed

    Hello, I just released a new version of my OpenSource project (http://sourceforge.net/projects/jdbcmanager).
    The application needs JRE 1.5 just only for printing tables (JTable.getPrintable(...) method).
    I have had a lot of complains from users due to requiring 1.5
    So I'm trying to make it compatible with 1.4.2 and also provide JTable printing functionality to 1.5 users.
    I can check if JRE in use is 1.5 and then invoke getPrintable(...) method via reflection, but I do not find a way to pass its first argument (an enum) via reflection, because in 1.4.x enum type does not exist, and without solving this the compiler reports a compilation error.
    Here is the code I'm using:String sJavaVer = System.getProperty( "java.version" );
           if( sJavaVer.charAt( 0 ) == '1' && sJavaVer.charAt( 2 ) < '5' )
               MessageFormat mfHeader = new MessageFormat( sHeader );
               MessageFormat mfFooter = new MessageFormat( sFooter );
               Printable     p        = getPrintable( PrintMode.FIT_WIDTH, mfHeader, mfFooter );
               PrintShop     ps       = new PrintShop( p );
               if( bPreview )
                   ps.showPreview( "Preview: "+ sHeader, getPreferredScrollableViewportSize() );
               else
                   ps.print( bPageDialog );
           else
               App.showMessage( "Warning", "You need JRE 1.5.0 or above to be able to print tables." );
           }Obviously this can't compile under 1.4.x
    Every suggestion is more than welcome.

    I haven't worked with 1.5 enums, but my best guess is that you'd have to get instances of the enums via reflection as well.
    As an incidental suggestion: rather than doing a text search on the "java.version" property, you should simply try to retrieve the "getPrintable" method via reflection. The "if" condition then checks to see if you got anything back.

  • Enums with constant-specific method implementation

    Just faced the following problem. I have a persistent class with one of the fields of it is enum with constant-specific method implementation:
    @Persistent
    public class Message
       static public enum Type
           DEFAULT
               @Override
               public String getDescription() { return "Some description"; }
           public abstract String getDescription();
       private Type type;
    }When I try to store the record, I get the exception:
    java.lang.IllegalArgumentException: Class could not be loaded or is not persistent: messages.Message$Type$1The problem seem to be in that compiler creates a separate class, namely Message$Type$1.class for the DEFAULT instance and this class is not known by BDB..
    If I remove the constant-specific method from enum, everything's working fine (as the ..$1.class is not created by compiler).. Except the fact that I'd like to have constant-specific methods there..
    Any ideas on this? Maybe it's a bad idea to create constant-specific methods if it means that each constant would get own class file (and they would bloat the storage routines)?

    Hi Mikhail,
    I recreated the problem here and you're right, constant-specific methods aren't working. This isn't something we thought about, to be honest, or tested.
    Just based on an initial quick look I see that for the compiler generated class, the Class.isEnum method returns false, which is why we don't recognize this as an enum and eventually why we throw the exception you're seeing. But assuming that we can identify the class as an enum (that shouldn't be too difficult) I don't know what other problems we will run into in trying to support this.
    For now I think the best thing is to avoid using the constant-specific methods. I have opened a ticket (#18357) so that we'll remember to look into this in more detail and see whether it can be supported in the future.
    If we are able to support it, then I'm hoping that we won't to store extra metadata for constants that have methods. In other words, I'm hoping that we won't have to add any extra storage or processing overhead.
    --mark                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Trying to pass and object variable to a method

    I have yet another question. I'm trying to display my output in succession using a next button. The button works and I get what I want using test results, however what I really want to do is pass it a variable instead of using a set number.
    I want to be able to pass the object variables myProduct, myOfficeSupplies, and maxNumber to method actionPerformed so they can be in-turn passed to the displayResults method which is called in the actionPerformed method. Since there is no direct call to actionPerformed because it is called within one of the built in methods, I can't tell it to receive and pass those variables. Is there a way to do it without having to pass them through the built-in methods?
    import javax.swing.JToolBar;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.JPanel;
    import java.net.URL;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class Panel extends JPanel implements ActionListener
         protected JTextArea myTextArea;
         protected String newline = "\n";
         static final private String FIRST = "first";
         static final private String PREVIOUS = "previous";
         static final private String NEXT = "next";
         public Panel( Product myProduct, OfficeSupplies myOfficeSupplies, int maxNumber )
                 super(new BorderLayout());
              int counter = 0;
                 //Create the toolbar.
                 JToolBar myToolBar = new JToolBar( "Still draggable" );
                 addButtons( myToolBar );
                 //Create the text area used for output.
                 myTextArea = new JTextArea( 450, 190 );
                 myTextArea.setEditable( false );
                 JScrollPane scrollPane = new JScrollPane( myTextArea );
                 //Lay out the main panel.
                 setPreferredSize(new Dimension( 450, 190 ));
                 add( myToolBar, BorderLayout.PAGE_START );
                 add( scrollPane, BorderLayout.CENTER );
              myTextArea.setText( packageData( myProduct, myOfficeSupplies, counter ) );
              setCounter( counter );
         } // End Constructor
         protected void addButtons( JToolBar myToolBar )
                 JButton myButton = null;
                 //first button
                 myButton = makeNavigationButton( FIRST, "Display first record", "First" );
                 myToolBar.add(myButton);
                 //second button
                 myButton = makeNavigationButton( PREVIOUS, "Display previous record", "Previous" );
                 myToolBar.add(myButton);
                 //third button
                 myButton = makeNavigationButton( NEXT, "Display next record", "Next" );
                 myToolBar.add(myButton);
         } //End method addButtons
         protected JButton makeNavigationButton( String actionCommand, String toolTipText, String altText )
                 //Create and initialize the button.
                 JButton myButton = new JButton();
                     myButton.setActionCommand( actionCommand );
                 myButton.setToolTipText( toolTipText );
                 myButton.addActionListener( this );
                   myButton.setText( altText );
                 return myButton;
         } // End makeNavigationButton method
             public void actionPerformed( ActionEvent e )
                 String cmd = e.getActionCommand();
                 // Handle each button.
              if (FIRST.equals(cmd))
              { // first button clicked
                          int counter = 0;
                   setCounter( counter );
                 else if (PREVIOUS.equals(cmd))
              { // second button clicked
                   counter = getCounter();
                      if ( counter == 0 )
                        counter = 5;  // 5 would be replaced with variable maxNumber
                        setCounter( counter );
                   else
                        counter = getCounter() - 1;
                        setCounter( counter );
              else if (NEXT.equals(cmd))
              { // third button clicked
                   counter = getCounter();
                   if ( counter == 5 )  // 5 would be replaced with variable maxNumber
                        counter = 0;
                        setCounter( counter );
                      else
                        counter = getCounter() + 1;
                        setCounter( counter );
                 displayResult( counter );
         } // End method actionPerformed
         private int counter;
         public void setCounter( int number ) // Declare setCounter method
              counter = number; // stores the counter
         } // End setCounter method
         public int getCounter()  // Declares getCounter method
              return counter;
         } // End method getCounter
         protected void displayResult( int counter )
              //Test statement
    //                 myTextArea.setText( String.format( "%d", counter ) );
              // How can I carry the myProduct and myOfficeSupplies variables into this method?
              myTextArea.setText( packageData( product, officeSupplies, counter ) );
                 myTextArea.setCaretPosition(myTextArea.getDocument().getLength());
             } // End method displayResult
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event dispatch thread.
         public void createAndShowGUI( Product myProduct, OfficeSupplies myOfficeSupplies, int maxNumber )
                 //Create and set up the window.
                 JFrame frame = new JFrame("Products");
                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                 //Add content to the window.
                 frame.add(new Panel( myProduct, myOfficeSupplies, maxNumber ));
                 //Display the window.
                 frame.pack();
                 frame.setVisible( true );
             } // End method createAndShowGUI
         public void displayData( Product myProduct, OfficeSupplies myOfficeSupplies, int maxNumber )
              JTextArea myTextArea = new JTextArea(); // textarea to display output
              JFrame JFrame = new JFrame( "Products" );
              // For loop to display data array in a single Window
              for ( int counter = 0; counter < maxNumber; counter++ )  // Loop for displaying each product
                   myTextArea.append( packageData( myProduct, myOfficeSupplies, counter ) + "\n\n" );
                   JFrame.add( myTextArea ); // add textarea to JFrame
              } // End For Loop
              JScrollPane scrollPane = new JScrollPane( myTextArea ); //Creates the JScrollPane
              JFrame.setPreferredSize(new Dimension(350, 170)); // Sets the pane size
              JFrame.add(scrollPane, BorderLayout.CENTER); // adds scrollpane to JFrame
              JFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); // Sets program to exit on close
              JFrame.setSize( 350, 170 ); // set frame size
              JFrame.setVisible( true ); // display frame
         } // End method displayData
         public String packageData( Product myProduct, OfficeSupplies myOfficeSupplies, int counter ) // Method for formatting output
              return String.format( "%s: %d\n%s: %s\n%s: %s\n%s: %s\n%s: $%.2f\n%s: $%.2f\n%s: $%.2f\n%s: $%.2f",
              "Product Number", myOfficeSupplies.getProductNumber( counter ),
              "Product Name", myOfficeSupplies.getProductName( counter ),
              "Product Brand",myProduct.getProductBrand( counter ),
              "Number of Units in stock", myOfficeSupplies.getNumberUnits( counter ),
              "Price per Unit", myOfficeSupplies.getUnitPrice( counter ),
              "Total Value of Item in Stock is", myOfficeSupplies.getProductValue( counter ),
              "Restock charge for this product is", myProduct.restockingFee( myOfficeSupplies.getProductValue( counter ) ),
              "Total Value of Inventory plus restocking fee", myOfficeSupplies.getProductValue( counter )+
                   myProduct.restockingFee( myOfficeSupplies.getProductValue( counter ) ) );
         } // end method packageData
    } //End Class Panel

    multarnc wrote:
    My instructor has not been very forthcoming with assistance to her students leaving us to figure it out on our own.Aren't they all the same! Makes one wonder why they are called instructors. <sarcasm/>
    Of course it's highly likely that enough information was imparted for any sincere, reasonably intelligent student to actually figure it out, and learn the subject in the process.
    And if everything were spoonfed, how would one grade the performance of the students? Have them recite from memory
    public class HelloWorld left-brace
    indent public static void main left-parenthesis String left-bracket right-bracket args right-parenthesis left-brace
    And everywhere that Mary went
    The lamb was sure to go
    db

  • How to pass a file into a java method

    I am trying to pass a file into a java method so I can read the file from inside the method. How can I do this? I am confident passing int, char, arrays etc into methods as I know how to identify them in a methods signature but I have no idea how to decalre a file in a mthods signature. Any ideas please ?
    Thanks

    Hi,
    Just go thru the URL,
    http://www6.software.ibm.com/devtools/news1001/art24.htm#toc2
    I hope you will get a fair understanding of 'what is pass by reference/value'.
    You can pass Object reference as an argument.
    What Pablo Lucien had written is right. But the ideal situation is if you are not modifying the
    file in the calling method, then you can pass the String (file name) as an argument to the called method.
    Sudha

  • Custom Tag: pass my own type in as attribute

    I thought I can pass any type as attribute into my custom tag. I tried, but failed. The exception is:
    org.apache.jasper.JasperException: Unable to convert '${myType}' to class MyTpye for attribute myAttribute: java.lang.IllegalArgumentException: Property Editor not registered with the PropertyEditorManager.
    I know I can pass the value in using PageContext attribute. However, still want to figure out how to do it through custom tag attribute.
    Here's my taglig file:
    <tag>
    <name>myTag</name>
    <tag-class>MyTagClass</tag-class>
    <body-content>empty</body-content>
    <attribute>
    <name>myAttribute</name>
    <required>true</required>
    <rtexprvalue>true</rtexprvalue>
    <type>MyType</type>
    </attribute>
    </tag>
    What am I missing here? Thanks.

    Hi
    Pls tell me how did you resolve this issue. I am also facing the same problem.
    Thanks
    Prakash

Maybe you are looking for

  • ICal in Day view doesn't show hours, but Days for the hours?

    Ok, so I have been trying to figure this out but I cannot find the answer. In iCal, I cannot change the hour of a new event. It only allows me to change the min. So I went into the Day view to try and move the events to the correct hours and all it s

  • UME: SAP R/3 system config

    I'm trying to set User authentication to SAP R/3 system, not load balanced system, on the User Management Configuration values: Client=601, Userid=sapjsf, Password=pwd, sys id=s01, Group and Message server= no values, Application server= IP addreess,

  • Multiple source systems ?

    Hi all, What is the best possible answer/solution for the following scenario If I am extracting same data(datasource) from multiple (say 3)R/3 source systems ie the datasources too are same for example 2lis_40_S600, how can we model the architecture

  • Problem syncing movies to ipd - Blue dots??

    I have 22 movies (films and clips) on my itunes account but when I sync to my ipod (80gb classic) only 10-12 seem to go on it. More so that the ammount, when I look at choosing the videos manually to go on the ipod, a number of them have a blue dot o

  • IWeb-No way to publish only 'updated' files?

    I am gathering by everyone's comments that there is no feature in iWeb to only update changed files, pages, etc? Please help if I am incorrect on this one. This seems like a major goof on apple's part ... I just wanted to change some font color today