The predecessor to the "typesafe enum pattern"

In 1998, Michael Bridges published the following on Dr.Dobb's Portal
(http://www.ddj.com/windows/184403569):
class BookAgeLevel
private BookAgeLevel(){}    
// Following are all the BookAgeLevel objects    
// there will ever be.    
final static BookAgeLevel TODDLER = new BookAgeLevel();    
final static BookAgeLevel CHILD = new BookAgeLevel();    
final static BookAgeLevel TEENAGER = new BookAgeLevel();    
final static BookAgeLevel ADULT = new BookAgeLevel();    
}In 1999, Nigel Warren and Philip Bishop refers to the exact same pattern as the "typesafe
constant idiom" in their book "Java in Practice" (page 48):
public final class Alienrace
  public static final AlienRace BORG = new Alienrace();
  public static final AlienRace FERENGI = new Alienrace();
  private AlienRace() {}
}In 2000, Joshua Bloch refers to the following code as the "typesafe enum pattern" (http://java.sun.com/developer/Books/shiftintojava/page1.html):
// The typesafe enum pattern
public class Suit {
    private final String name;
    private Suit(String name) { this.name = name; }
    public String toString()  { return name; }
    public static final Suit CLUBS = new Suit("clubs");
    public static final Suit DIAMONDS = new Suit("diamonds");
    public static final Suit HEARTS = new Suit("hearts");
    public static final Suit SPADES = new Suit("spades");
}

sunfun99 wrote:
No point, just interesting. There is no question attached to this.OK - I still have a load of code in both C++ and Java that uses this Pattern ( it ain't broke so I ain't fixing it) and I first started using this in C++ in about 1987 (God 20 years ago). I didn't invent it for myself so it must be older than that.

Similar Messages

  • PersistenceDelegate for typesafe enum pattern

    I've converted my code over from using int constants to the typesafe enum pattern in Effective Java. Unfortunately, the pattern only goes into serialization using Serializable and does not go into how to write a proper PersistenceDelegate that parallels the safety precautions of the Serializable enum. I've tried to do a direct mirroring of the readResolve() method given in the book inside of the intiatiate method of my PersistenceDelegate, but the XMLEncoder keeps rejecting the output and I get an InstantiationException, which shouldn't happen since the method call should not instantiate any new instances since the enums are static.
    class PositionBiasModePersistenceDelegate extends PersistenceDelegate {
        protected Expression instantiate(Object oldInstance, Encoder out) {
            PositionBiasMode mode = (PositionBiasMode) oldInstance;
            return new Expression(mode, PositionBiasMode.VALUES, "get", new Object[] {new Integer(PositionBiasMode.VALUES.indexOf(mode))});
    public abstract class PositionBiasMode {
        private final String name;
        private static int nextOrdinal = 0;
        private final int ordinal = nextOrdinal++;
        /** Creates a new instance of PreferredPositionMode */
        private PositionBiasMode(String name) {
            this.name = name;
        public String toString() {
            return name;
        public abstract boolean complies(PositionBias pb);
        public static final PositionBiasMode IGNORE = new PositionBiasMode("Ignore") {
            public boolean complies(PositionBias pb) {
                return true;
        public static final PositionBiasMode FRONT = new PositionBiasMode("Front") {
            public boolean complies(PositionBias pb) {
                return pb.hasBias() && pb.getPositionBias() < 0 ? false : true;
        public static final PositionBiasMode BACK = new PositionBiasMode("Back") {
            public boolean complies(PositionBias pb) {
                return pb.hasBias() && pb.getPositionBias() >= 0 ? false : true;
        private static final PositionBiasMode[] PRIVATE_VALUES = {IGNORE, FRONT, BACK};
        public static final List VALUES = Collections.unmodifiableList(Arrays.asList(PRIVATE_VALUES));
    }

    Yeah I tried this too. I think the instantiation exception is something to do with it trying to recreate the MyEnum.VALUES List. I don't understand enough about the process to know how to fix that though.
    The approach I eventually went for was to add a couple of things to the enum class as follows:
    // add to MyEnum class:
    public static final PersistenceDelegate PERSISTENCE = new PersistenceDelegate()
         protected boolean mutatesTo(Object oldInstance, Object newInstance)
              return (MyEnum)oldInstance == (MyEnum)newInstance;
         protected Expression instantiate(Object oldInstance, Encoder out)
              MyEnum enum = (MyEnum)oldInstance;
              return new Expression(enum, new MyEnum.Factory(), "forOrdinal", new Object[]{new Integer(enum.ordinal)});
    public static final class Factory
         public MyEnum forOrdinal(int ordinal)
              return PRIVATE_VALUES[ordinal];
    // usage:
    XMLEncoder enc = new XMLEncoder(...);
    enc.setPersistenceDelegate(MyEnum.class, MyEnum.PERSISTENCE);Not entirely sure it's the ideal approach but maybe it'll work for you. Cheers.

  • Typesafe enum pattern

    Hi all,
    In the “Effective Java Programming Language Guide” by: “Joshua Bloch”, chapter: 5, item: 21, I came across the following:
    +“Constants maybe added to a typesafe enum class w/o recompiling its clients b/c the public static object reference fields containing the enumeration constants provide a layer of insulation bet. the client and the enum class.+
    What does that mean?
    The constants themselves are never compiled into clients as they are in the more common int enum pattern and its String variant.”
    What does that mean?
    Can someone please explain the above in more detail or guide me in another doc./article which helps me get the point?
    Any help is greatly appreciated.
    Edited by: RonitT on Apr 20, 2009 2:53 PM

    In any case, that item should be updated now to advise you to use the Enum types introduced in 1.5 instead of rolling yer own. You are right, I'll use that instead - looks like I have an old edition of book!
    Anyway. just for me to understand what you mentioned, since the client code sees the value of RANDOM -- like 17 and not 42 -- so let say my client code has the constants 0 thru 10 and now I need to add new constants from 11 to 20, if I'm confident that my client will never need these new constants, I don't need to give them the new code which contains the values 11 thru 20, is that right? That was you were trying to tell me?
    Thanks again.

  • ORing TypeSafe enums together

    I have tranaslated an enum type from C using the "typesafe enum pattern" (see, e.g. Bloch: Effective Java, p.104). I want to OR two of the enum values together. E.g.
    Classname.FIRST | Classname.SECOND
    but because they are instances of a class and not int values I get an "operator cannot be applied..." error from the compiler. How can I augment/modify the class to make this operation legal and correct?
    Many thanks.

    You would need to associate an integer ordinal with each enum. Josh demonstrates something like this later in the chapter for an enum that implements Comparable. Since you want to work with bitwise values, you'll need to make each successive ordinal a power of two so each enum maps to one bit. It might look something like this: public class MyEnum implements Comparable {
        /** ordinal of next enum to be created */
        static private int nextOrdinal = 1 ;
        /** returns next ordinal to assign */
        static private int getNextOrdinal() {
            int thisOrd = nextOrdinal ;
            nextOrdinal <<= 1 ;
            return thisOrd ;
        /** face name of this enum */
        private final String name ;
        /** bitwise ordinal for this enum */
        private final int ordinal = getNextOrdinal() ;
        private MyEnum(String name)    { this.name = name ; }
        public String toString()       { return name ; }
        public int getOrdinal()        { return ordinal ; }
        public int compareTo(Object o) { return ordinal - ((MyEnum)o).ordinal ; }
        static public final MyEnum FIRST  = new MyEnum("First") ;
        static public final MyEnum SECOND = new MyEnum("Second") ;
        static public final MyEnum THIRD  = new MyEnum("Third") ;
        static public final MyEnum FOURTH = new MyEnum("Fourth") ;
    } Then, two enums are "OR'd" together like so: MyEnum.FIRST.getOrdinal() | MyEnum.SECOND.getOrdinal().

  • Typesafe enums - 1.5

    In the interview Joshua Bloch states the the new 1.5 feature "Typesafe enums - Provides all the well-known benefits of the Typesafe Enum pattern"
    Does it also provide the pitfalls? The typesafe enum pattern is nice. However, in a multi-classloader environment it can behave unexpectedly. Similar to the Singleton pattern, it is generally best to avoid it in app-server code.
    Does the 1.5 implementation essentially compile to the pre-1.5 manual implementation or does it deal with this issue?

    you can overcome the and .equals() failing with a very minor amount of code. Basically you need a set of all possible typesafe values.
    Additionally you need to implement readResolve to prevent serialization from cloning.
    Finally - it's just never a good idea to use == for equality comparison. It should only be used for identity comparison (and even then most of the time you should have equals perform the identity comparison).
        private static final Stooge[] ALL = new Stooge{Moe, Larry, Curly};
        //see java.io.Serializable for details
        protected Object readResolve() throws ObjectStreamException {
            return getTypeFor(this.name);
        //you usually need this for retrieval from persistent storage
        public static Stooge getTypeFor(String name){
          Stooge result = null;
          for(int i = 0; i < ALL.length; i++){
            if(ALL.name.equals(name)){
    result = ALL[i];
    break;
    return result;

  • Using the Model Facade Pattern in a Java EE 5 Web application

    Hi,
    Yutaka and I did a Tech tip
    http://java.sun.com/mailers/techtips/enterprise/2006/TechTips_Nov06.html#2 on using a model facade pattern in Java EE 5 web-only applications recently. We got some questions about it, and these were some of the questions raised...
    Question 1) the first part of the tech tip(it has two articles in it) http://java.sun.com/mailers/techtips/enterprise/2006/TechTips_Nov06.html showed how to access Java Persistence objects directly from a JSF managed bean, is this a good practice?
    Question 2) when to use a facade(as mentioned in the second part of tech tip) ?
    and maybe
    Question 3) why doesn't the platform make this easier and provide the facade for you?
    Briefly, I will take a shot at answering these three questions
    Answer 1) You can access Java persistence directly from your managed beans, but as your application grows and you start to add more JSF managed beans or other web components(servlets, JSP pages etc) that also directly access Java Persistence objects, you will start to see that you are cutting/pasting similiar code to handle the transactions and to handle the Java Persistence EntityManager and other APIs in many places. So for larger applications, it is a good practice to introduce a model facade to centralize code and encapsulate teh details of the domain model management
    Answer 2) IAs mentioned in answer 1, its good to use a model facade when your application starts to grow. For simple cases a spearate model facade class may not be needed and having managed beans do some of the work is a fast way to jumpstart you application development. But a facade can help keep the code clean and easier to maintain as the aplication grows.
    Answer 3) First note that both of the articles in the tech tip were about pure web apps(not using any EJBs) and running on the Java EE5 platform. Yes it would be nice if a facility like this was made available for web-only applications(those not using EJBs). But for web-only applications you will need to use a hand-rolled facade as we outlined in the tech tip. The Java EE platform does provide a way to make implementing a facde easier though, and the solution for that is to use a Session Bean. This solution does require that you use ythe EJB container and have a Session Bean facade to access your Java Persistence objects and manage the transactions. The EJB Session Facade can do a lot of the work for you and you dont have to write code to manage the transactions or manage the EntityManager. This solution was not covered in this tech tip article but is covered in the Java BluePrints Solutions Catalog for Perssitence at
    https://blueprints.dev.java.net/bpcatalog/ee5/persistence/facade.html in the section "Strategy 2: Using a Session Bean Facade" . Maybe we can cover that in a future tech tip.
    Please ask anymore questions about the tech tip topic on this forum and we will try to answer.
    hth,
    Sean

    Hi Sean,
    I'm working on an implementation of the Model Facade pattern where you can possibly have many facades designed as services. Each service extends a basic POJO class which I'm calling CRUDService: its short code is provided below for your convenience.
    The CRUDService class is meant to generalize CRUD operations regardless of the type of the object being used. So the service can be called as follows, for example:
    Job flightAtt = new Job();
    SERVICE.create(flightAtt);
    Runway r = (Runway) SERVICE.read(Runway.class, 2);
    Employee e = (Employee) SERVICE.read(Employee.class, 4);
    SERVICE.update(e);
    SERVICE.delete(r);SERVICE is a Singleton, the only instance of some service class extending CRUDService. Such a class will always include other methods encapsulating named queries, so the client won't need to know anything about the persistence layer.
    Please notice that, in this scenario, DAOs aren't needed anymore as their role is now distributed among CRUDService and its subclasses.
    My questions, then:
    . Do you see any obvious pitfalls in what I've just described?
    . Do you think traditional DAOs should still be used under JPA?
    . It seems to me the Model Facade pattern isn't widely used because such a role can be fulfilled by frameworks like Spring... Would you agree?
    Thanks so much,
    Cristina Belderrain
    Sao Paulo, Brazil
    public class CRUDService {
        protected static final Logger LOGGER = Logger.
            getLogger(Logger.GLOBAL_LOGGER_NAME);
        protected EntityManager em;
        protected EntityTransaction tx;
        private enum TransactionType { CREATE, UPDATE, DELETE };
        protected CRUDService(String persistenceUnit) {
            em = Persistence.createEntityManagerFactory(persistenceUnit).
                createEntityManager();
            tx = em.getTransaction();
        public boolean create(Object obj) {
            return execTransaction(obj, TransactionType.CREATE);
        public Object read(Class type, Object id) {
            return em.find(type, id);
        public boolean update(Object obj) {
            return execTransaction(obj, TransactionType.UPDATE);
        public boolean delete(Object obj) {
            return execTransaction(obj, TransactionType.DELETE);
        private boolean execTransaction(Object obj, TransactionType txType) {
            try {
                tx.begin();
                if (txType.equals(TransactionType.CREATE))
                    em.persist(obj);
                else if (txType.equals(TransactionType.UPDATE))
                    em.merge(obj);
                else if (txType.equals(TransactionType.DELETE))
                    em.remove(obj);
                tx.commit();
            } finally {
                if (tx.isActive()) {
                    LOGGER.severe(txType + " FAILED: ROLLING BACK!");
                    tx.rollback();
                    return false;
                } else {
                    LOGGER.info(txType + " SUCCESSFUL.");
                    return true;
    }

  • What is the best design pattern for this problem?

    No code to go with the question. I am trying to settle on the best design pattern for the problem before I code. I want to use an Object Oriented approach.
    I have included a basic UML diagram of what I was thinking so far. 
    Stated simply, I have three devices; Module, Wired Modem, and Wireless Modem.
    In the Device Under Test parent class, I have put the attributes that are variable from device to device, but common to all of them.
    In the child classes, I have put the attributes that are not variable to each copy of that device. The attributes are common across device types. I was planning to use controls in the class definition that have the data set to a default value, since it doesn't change for each serial number of that device. For example, a Module will always have a Device Type ID of 1. These values are used to query the database.
    An example query would be [DHR].[GetDeviceActiveVersions] '39288', 1, '4/26/2012 12:18:52 PM'
    The '1' is the device type ID, the 39288 is the serial number, and the return would be "A000" or "S002", for example.
    So, I would be pulling the Serial Number and Device Type ID from the Device Under Test parent and child, and passing them to the Database using a SQL string stored in the control of the Active Versions child class of Database.
    The overall idea is that the same data is used to send multiple queries to the database and receiving back various data that I then evaluate for pass of fail, and for date order.
    What I can't settle on is the approach. Should it be a Strategy pattern, A Chain of Command pattern, a Decorator pattern or something else. 
    Ideas?

    elrathia wrote:
    Hi Ben,
    I haven't much idea of how override works and when you would use it and why. I'm the newest of the new here. 
    Good. At least you will not be smaking with a OPPer dOOPer hammer if I make some gramatical mistake.
    You may want to look at this thread in the BreakPoint where i trie to help Cory get a handle on Dynamic Dispatching with an example of two classes that inherit from a common parent and invoke Over-ride VIs to do the same thing but with wildly varying results.
    The example uses a Class of "Numeric"  and a sibling class "Text" and the both implement an Add method.
    It is dirt simple and Cory did a decent job of explaining it.
    It just be the motivation you are looking for.
    have fun!
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • Use of synchronisation with the SUN DAO Pattern

    With reference to the design pattern Core J2EE Patterns Data Access Object: http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html
    I am writing a DAO package to handle access to multiple datasources at a record level (e.g. user records may be located at datasource A, but customer records at datasource B). The role of the package is to provide DAO objects to clients (e.g. business objects in an application package to come later). Nothing too unusual. I have digested the SUN design pattern for DAO.
    As I understand it, it can be summarised as: client code calls on an abstract DAOFactory to provide the appropriate concrete DAOFactory . The concrete factory can then supply the correct DAO object. The concrete DAOFactory is also responsible for providing the connection services (such as pooling). So far so good. I have pasted the concrete DAOFactory code form the design pattern page:
    // Cloudscape concrete DAO Factory implementation
    import java.sql.*;
    public class CloudscapeDAOFactory extends DAOFactory {
    public static final String DRIVER=
    "COM.cloudscape.core.RmiJdbcDriver";
    public static final String DBURL=
    "jdbc:cloudscape:rmi://localhost:1099/CoreJ2EEDB";
    // method to create Cloudscape connections
    public static Connection createConnection() {
    // Use DRIVER and DBURL to create a connection
    // Recommend connection pool implementation/usage
    *** can a connection pool be implemented in a static method? ***
    public CustomerDAO getCustomerDAO() {
    // CloudscapeCustomerDAO implements CustomerDAO
    return new CloudscapeCustomerDAO();
    public AccountDAO getAccountDAO() {
    // CloudscapeAccountDAO implements AccountDAO
    return new CloudscapeAccountDAO();
    public OrderDAO getOrderDAO() {
    // CloudscapeOrderDAO implements OrderDAO
    return new CloudscapeOrderDAO();
    I have some questions on this overall design.
    1)     The design for the factories as given looks inelegant and requires upgrading each time a new DAO is added ? much better surely to dynamically generate the DAOs using reflection. If I implement a mapping of data type to data source using a properties file (typical entry, Key = Role, Value = Oracle), the use of abstract and concrete factories can be reduced to a single factory. The single factory reads in the mapping on initialisation and provides a method getDAO to client code. The method takes the data type, looks up the data source and returns the correct DAO class using reflection (e.g. the client passes ?Role? to getDAO and the factory returns Oracle + DAO + Role = OracleDAORole.class). This also has the advantage that the client code does not need to specify the data source to use. I have read some forums and note that performance is an issue with reflection; however I have not seen any significant difference in performance between using reflection to generate a class name and using a factory pattern (e.g. testing just the code paths, for 10 million operations, both reflection and factory took 2.5 seconds each). Does anyone have any opinions on the pros and cons of this approach?
    2)     If we go with the original DAO design (ignoring 1 above) I have marked the part of the concrete factory code that I have a problem with: using a connection pool in the concrete factory. As the factory?s createConnection method is static, you cannot use NotifyAll or Wait methods here, and therefore you cannot synchronise access to the pool (correct?). I have therefore created a separate connection pool class (which uses the singleton pattern and uses synchronised methods to manage the pool). Is this a sensible way to approach this or is there a clever way to synchronise access to static methods?
    Thanks in advance - Alan

    These resources may be helpful:
    http://daoexamples.sourceforge.net/related.html
    http://daoexamples.sourceforge.net/index.html

  • The business delegate pattern in petstore

    hello
    who can tell me which class in the petstore implement the business delegate pattern.
    otherwise,who can tell me which website provide sample code for the j2ee design psttern.
    thank you very much!

    Session beans are usually an application of a Business Delegate pattern.
    Web Browserable source
    http://java.sun.com/blueprints/code/jps131/src/index.html
    Other J2ee stuff.
    http://java.sun.com/blueprints/code/jps131/docs/index.html

  • The "ValueList Handler" pattern in "Core j2ee patterns(2nd ed)"

    In the book "Core j2ee patterns(2nd ed)", it suggests that the "ValueList Handler" pattern can be used when the resultset from database is huge.
    Basically, this is what it will do:
    1) obtain a resultset from database query
    2) cache the full resultset using a valueList
    3) create a subList from the valueList
    4) present the subList to the front end
    To me, caching the full resultset in a valueList is no different from sending the full resultset to the front end. Both of them wasted a lot of resources. I am wondering why anyone would want to do the step(2) above. Why don't we go from (1) to (3) directly since we usually know which subset of the results the users are interested in even before we do the query.

    Hi
    Same problem I also need to clarify. Please some one
    explain in detail which approach give high
    performance.
    BR
    SenakaExactly, I don't understand why that "ValueList Handler" pattern qualified itself as a j2ee pattern since it has so much negative perfomance impacts.
    On a website like Amazon, thousands of queries are performed daily. To cache the full resultset of every query simply wouldn't work.
    I think the most efficient way is to write a disconnected resultset so it won't tie to the database. The disconnected resultset will only contains those data to be display on the front end.
    I would really like to see somthing like the following in the JDBC API.
    ResultSet rs = null; // some resultset
    ResultSetFilter filter = null;  // a filter to filter resultsets
    // obtain a disconnected resultset from java.sql.ResultSet
    DisconnectedResultset drs = DisconnectedResultset.filter(rs, filter);
    // close the original resultset
    rs.close();In the above, anything that meets the condition specified in the filter will be stored in the disconnected resultset. After we created a disconnected resultset, it is safe to close the original resultset to release any database resources.

  • A place for the Presentation Model pattern?

    Following another discussion, I was wondering if the Presentation Model pattern, recently promoted by various AC members, should have a place in cairngorm's future implementation, and how.
    It has been said that this pattern is not directly part of cairngorm scope. I agree with this, however, I wonder if some sort of "guidance" could be implemented. For instance, the CairngormEvent class could have a property representing the PM that dispatched it. One could imagine an IPresentationModel interface (should it be empty), to help doing so. Or an AbstractPresentationModel implementing common behavior, such as handleFirstShow?
    Please note that I'm not trying to advocate any practice here. I may be completely wrong, as I may have misunderstood Paul Williams and Borre Wessel's articles and slides.
    What do you think?

    David -- we've been advocating the presentation model pattern within Adobe Consulting because we're currently using it ourselves in our Cairngorm projects that are of a particular scale.
    We'll be sharing our thinking more with this community in the near future -- you've obviously picked some of it up from Paul and Borre's articles, and your discussions with some of our team in Paris ?
    But I do see that the presentation model is essentially a refactoring that we trend towards - it's not "the simplest thing that works" for many projects, so the refactoring series I see is:
    1) Start with a ModelLocator class with very few bits of state on it
    2) Extract class refactoring on ModelLocator - avoid a monolithic ModelLocator by extracting out classes representing models, and ModelLocator is a tree of models
    3) Refactor towards Presentation Model pattern; this is where we want to empower our models to manage their own persisitence, particularly in data-oriented rather than service-oriented parts of our application
    4) Extract class refactoring on presentation model to extract a domain model class that may be shared amongst presentation models; this is the most complex/verbose solution that we find emerges in HUGE applications that we are developing
    We're not sure whether there's any infrastructure to add to Cairngorm 3, however we will be sharing this thinking and more through some technical guides that help developers understand how much complexity is appropriate in their model depending upon the scale of their application, and depending how service/data-oriented the application is ... with a well defined sequence of refactorings that can be applied as the complexity of the application emerges.

  • What is the best design pattern for top-down ws development..?

    Hi,
    What is the best design pattern for top-down development+ wsdl2service....?

    elrathia wrote:
    Hi Ben,
    I haven't much idea of how override works and when you would use it and why. I'm the newest of the new here. 
    Good. At least you will not be smaking with a OPPer dOOPer hammer if I make some gramatical mistake.
    You may want to look at this thread in the BreakPoint where i trie to help Cory get a handle on Dynamic Dispatching with an example of two classes that inherit from a common parent and invoke Over-ride VIs to do the same thing but with wildly varying results.
    The example uses a Class of "Numeric"  and a sibling class "Text" and the both implement an Add method.
    It is dirt simple and Cory did a decent job of explaining it.
    It just be the motivation you are looking for.
    have fun!
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • Mapping typesafe enums

    I have a class, one of it's attributes is a typesafe enum:
    public class Title {
         TitleType type;
         int titleId;
         String titleName;
         public TitleType getTitleType() {
              return this.type;
    public class TitleType {
         private final String name;
         private final int typeId;
         private TitleType(String name, int typeId) {
              this.name = name;
              this.typeId = typeId;
         public String toString() {
              return this.name;
         public int toInt() {
              return this.typeId;
         public static final TitleType MAIN_TITLE = new TitleType("MAIN", 1);
         public static final TitleType SUB_TITLE = new TitleType("SUB", 2);
    }My table is:
    TITLES (
    title_id numeric,
    title_type varchar,
    title_name varchar)
    How do I map the TitleType class/attributes' String value to the column title_type in titles?
    For a title with TitleType TitleType.MAIN_TITLE my table should look like:
    title_id     title_type     title_name
    1          MAIN          "The Guiness book of records"Regards,
    Anthony

    Thanks Doug,
    I created the AfterLoad class and unmapped the field.
    For some reason though all the titles loaded from the table are coming through as just "MAIN" TitleType.
    Heres the AfterLoad class:
    public class AfterLoad {
         public static void afterLoadTitle(Descriptor descriptor) {
              ObjectTypeMapping otm = new ObjectTypeMapping();
              otm.setAttributeName("titleType");
              otm.setFieldName("TITLE_TYPE");
              otm.addConversionValue(TitleType.MAIN_TITLE.toString(), TitleType.MAIN_TITLE);
              otm.addConversionValue(TitleType.SUB_TITLE.toString(), TitleType.SUB_TITLE);
              otm.addConversionValue(TitleType.TRANSLATED_TITLE.toString(), TitleType.TRANSLATED_TITLE);
              otm.setDescriptor(descriptor);
              descriptor.addMapping(otm);
    }Any idea why?
    Regards,
    Anthony

  • Extending typesafe enum

    Hello,
    I know that this topic is already cleared that not possible to extend typesafe enum.
    But I don't have any other solution than doing this.
    Here is my problem.
    I have 2 package.
    - package generated
    - package design
    The purpose of the programs is to wrapping package generated in package design, that the user of this program should not use even the smallest part of the package generated.
    package generated contains class A, B, and enum Type
    Here are the declarations:
    File: generated/Type.java
    package generated;
    package generated;
    enum Type
    read, write, readwrite;
    }File: generated/B.java
    package generated;
    public class B
    int num;
    void setNum(int num){this.num = num;}
    int getNum(){ return num;}
    }File: generated/A.java
    package generated;
    public Class A
    int num;
    Type type;
    B b;
    void setNum(int num){this.num = num;}
    int getNum(){ return num;}
    void setType(Type type){this.type = type;}
    Type getType(){ return type;}
    void setB(B b){this.b = b;}
    B getB(){ return b;}
    }Now inside package design:
    File: design/B.java
    package design;
    public class B
    extends generated.B
    }File: design/A.java
    package design;
    public Class A
    extends generated.A
    }Here is the problem:
    File: App.java
    import design.*;
    class App{
    public static void main(String args[])
      A a = new A();
    B b = new B();
    a.setB(b);
    //This part is not expected, while it's using the type of package generated
    //a.setType( generated.Type.write);
    }The problem here is by setting the type of class A. While the method setType of design.A is inherited from generated.A, I cannot setting the value of this type without using the Type from the package generated, even when I add a enum of Type in package design, it still doesn't work, while there couldn't be casted from design.Type to generated.Type.
    This problem is not arised with setB(), while design.B is the subclass of generated.B, and thus can be casted automatically.
    So I have no Idea how can I solve this thing.
    As a note, the package generated cannot be changed.
    If there are anybody have ever faced the same problem, maybe can share their experience.
    Thanks a lot in advance.
    Best regards,
    Heru

    Hi,
    thanks for the reply.
    I'm actually making an API of a data source using JAXB to generate Java Code from an XML schema.
    This generated package is going to have features added along the time. So the wrapper I make is to assure that the API still work when new functions/features added. If I don't create any Wrapper, my written code (extension of the generated code) would be replaced by the new generated code each time the new features added.
    The reason I restrict the user to access the generated package, is because I don't want to confuse the user to access around the generated package and the wrapper package. The purpose of this wrapper is to completely wrapping whole the function of the generated code.
    Hopefully my explanation is understandable.. :-)
    Do you have any other advice how to accomplish this?
    Thanks.
    Best regards,
    Heru

  • Typesafe Enums

    I do not use J2SE 5.0, and I need to use an enumerator-like construct. My original code was:
    // Constants to be used with runnersOnBase
    public static final short RUNNER_ON_FIRST = 1;
    public static final short RUNNER_ON_SECOND = 2;
    public static final short RUNNER_ON_THIRD = 4;Obviously this is not a great practice, so I decided to try typesafe enums, which are explained here: http://java.sun.com/developer/Books/shiftintojava/page1.html#replaceenums
    The problem I'm having comes from the fact that, in my program, I can add the integer constants together. Is there a similar way to do that with typesafe enums, and if so, how should the enum class be set up? Thanks a lot. Take care.

    The problem I'm having comes from the fact that, in
    my program, I can add the integer constants together.
    Is there a similar way to do that with typesafe
    enums, and if so, how should the enum class be set
    up? Thanks a lot. Take care.Something like
    public class Enum {
    private static Map enums;
    public static Enum A = new Enum();
    public static Enum B = new Enum();
    public static Enum C = new Enum();
    static {
       enums.add( Integer.valueOf( 0 ), A );
       enums.add( Integer.valueOf( 0 ), B );
       enums.add( Integer.valueOf( 0 ), C );
    public static Enum add( Enum a, Enum b ) {
       int av = enums.get( a );
       int bv = enums.get( b );
       Enum value = enums.get( Integer.valueOf( av + bv ) );
    //   if( value == null  ) throw some exception maybe?
       return value;
    }maybe?

Maybe you are looking for

  • Moving events from one iPhoto library to another

    I want to move some events from one iPhoto library to another.  Does anyone know that this is possible and if so, how do I do it?

  • ORA-00600 error when inserting NULL in BLOB column

    Hi, I want to insert NULL value into a BLOB column w/o using empty_blob(), but I am getting the following error upon submission (both through program and upon directly executing it from TOAD/SQL*): java.sql.SQLException: ORA-00600: internal error cod

  • Error runnning sample code on 64 bit windows

    Hello, I am using VS 2010 express to execute the sample SAP connector client code provided by dataxstream on windows 7 and I have installed the 64 bit version of the connector. I added the references required to execute the code, but I get the below

  • Elements 7: Why doesn't it open?

    When I have tried to open EL 7 a message comes up from Photoshop.com appears stating: Photoshop.com Membership "Gathering user info..." and then NOTHING happens. It ran for 30-40 minutes until I got fed up and turned it off in frustration. Please hel

  • Why is my iCal Server Delegation No Longer Available?

    I've recently reformatted a Mac Mini Server that was and is running the latest version of OS X Server. It is hosting a private domain for a local network of just a few client machines, and everyone has their own network user account. Yesterday I logg