Static methods in Transfer Objects

Hi all,
I have a doubt about Transfer Object:
Is it possible to have a static method (or field)
inside a Transfer Object returned from
a Session Bean to a Client ?
Many thanks in advance,
Moreno

Static fields, yeah, they'd cause some interesting problems, so are not a good idea in TOs. You can do it, but YMMV (Your Mileage May Vary).
Static method? I'd get rid of it and put it in a utility class or somewhere else. Static methods are pretty meaningless when applied to TOs. The idea is to encapsulate data and some behavior - not provide procedural functionality.

Similar Messages

  • JUNIT : how to call static methods through mock objects.

    Hi,
    I am writing unit test cases for an action class. The method which i want to test calls one static method of a helper class. Though I create mock of that helper class, but I am not able to call the static methods through the mock object as the methods are static. So the control of my test case goes to that static method and again that static method calls two or more different static methods. So by this I am testing the entire flow instead of testing the unit of code of the action class. So it can't be called as unit test ?
    Can any one suggest me that how can I call static methods through mock objects.

    The OP's problem is that the object under test calls a static method of a helper class, for which he wants to provide a mock class
    Hence, he must break the code under test to call the mock class instead of the regular helper class (because static methods are not polymorphic)
    that wouldn't have happened if this helper class had been coded to interfaces rather than static methods
    instead of :
    public class Helper() {
        public static void getSomeHelp();
    public class MockHelper() {
        public static void getSomeHelp();
    }do :
    public class ClassUnderTest {
        private Helper helper;
        public void methodUnderTest() {  // unchanged
            helper.getSomeHelp();
    public interface Helper {
        public void getSomeHelp();
    public class HelperImpl implements Helper {
        public void getSomeHelp() {
            // actual implementation
    public class MockHelper implements Helper {
        public void getSomeHelp() {
            // mock implementation
    }

  • Creating  a static method returning Logger Object inside class

    Hello,
    Instead of creating Logger Instance in every class , can i do like this way by creating a static method in some class returning a Logger object , and using that method for getting instance of Logger in another class through that method
    Regards
    Mayur Mitkari

    On a related note, if you want to make it simpler, never do this:
    if (a == true)Instead, just do if (a)It's pointless and cluttersome to use == or != with true or false.
    // wrong
    if (a == true)
    if (a != false)
    // right
    if (a)
    // wrong
    if (a == false)
    if (a != true)
    // right
    if (!a)Also, note that
    if (x) {
      return true;
    else {
      return false;
    }can be simplified to return x;If you do that and change your variable to something a bit more meaningful, like trueCount or numTrue or something, your code would be
    int trueCount = 0;
    if (a) trueCount++;
    if (b) trueCount++;
    if (c) trueCount++;
    return trueCount >= 2;which is about as simple and clear as it can get, IMHO. Using less code doesn't necessarily make the code simpler or clearer. The idea is that someone reading the code can easily understand what it does.
    And note that the above can be easily generalized to "Are there at least M true values in this array/list of N booleans?" and still be concise and clear.

  • Implementation of static methods in Custom Controls

    I'm using Custom Java Controls to implement business objects in a workshop web application.
    I've designed a number of static methods into the object model for logically static operations (i.e. operations related to the Business object but not requiring an instance).
    Since workshop generates the control interface as a java interface, it is not possible to declare static methods on the control interface. I have tested implementing the interface as an abstract class and setting @editor-info:code-gen control-interface="false" on the control. This seems to work, but then we lose code generation.
    Other options include:
    - Put the static method on the Impl and call directly (don't like this, breaks encapsulation)
    - Make it non-static (don't like this, prevents compiler checks for refs to non-static members)
    Has anyone found an elegant way to do this in workshop without losing code gen features? Any ideas welcome...
    TIA
    Jim

    Please guys someone tell me the answer for this question. I guess its a valid question, though I feel that the answer to this question must be quiet easy since somewhere the methods must have been getting implemented.
    Please let me know who does that and how and when!!!
    Hoping for an explanation to this now

  • What is the advantage of using methods to return objects?

    Hello there,
    What is the advantage of using static methods to return
    objects? Isnt this a Factory Pattern ?
    What is the real advantage of using methods to return objects
    rather than using public constructors to create objects ?
    Can some one please explain
    Regards

    I think there were two questions. The first (why
    static) is well answered but I hope somebody can
    answer the general question - why whatever =
    createSomething(); as opposed to whatever
    = new Something(); - because inquiring minds
    want to know.I thought I answered that question. Perhaps I need to be more specific.
    For the Singleton pattern, you don't want a new instance (except possibly the first time, if you're using lazy instantiation).
    For the Factory pattern, you might not always want an instance of the actual class containing the static methods, so new won't work.
    If, on the other hand, neither of the above holds, there is no reason not to use new (unless, of course, anyone can come up with another use of static creators).
    RObin

  • Synchronized static method???

    Hi!
    What does it means "synchronized static" method? What object in this case has a lock monitor?
    class MyClass  {
    public synchronized static someMethod() {
    }Is it the equivalent to:
    synchronized ( MyClass.class ) {
    Anton

    The JVM creates a Class object when the class is loaded (When it is used for the first time) the
    JVM creates one instance of Class for each class that is loaded, thus a class itself has a moniter
    which a thread can gain ownership of.

  • Using HttpServletRequest object to share variables between static methods.

    Does anyone know of the overhead/performance implications of using the HttpServletRequest object to share variables between a static method and the calling code?
    First, let me explain why I am doing it.
    I have some pagination code that I would like to share across multiple servlets. So I pulled the pagination code out, and created a static method that these servlets could all use for their pagination.
    public class Pagination {
         public static void setPagination (HttpServletRequest request, Config conf, int totalRows) {
              int page = 0;
              if (request.getParameter("page") != null) {
                   page = new Integer(request.getParameter("page")).intValue();
              int articlesPerPage = conf.getArticlesPerPage();
              int pageBoundary = conf.getPageBoundary();
                int numOfPages = totalRows / articlesPerPage;  
                // Checks if the page variable is empty (not set)
                if (page == 0 || (page > numOfPages && (totalRows % articlesPerPage) == 0 && page < numOfPages + 1)) {    
                 page = 1;  // If it is empty, we're on page 1
              // Ex: (2 * 25) - 25 = 25 <- data starts at 25
             int startRow = page * articlesPerPage - (articlesPerPage);
             int endRow = startRow + (articlesPerPage);           
             // Set array of page numbers.
             int minDisplayPage = page - pageBoundary;
             if (minDisplayPage < 1) {
                  minDisplayPage = 1;     
             int maxDisplayPage = page + pageBoundary;
             if (maxDisplayPage > numOfPages) {
                  maxDisplayPage = numOfPages;     
             int arraySize = (maxDisplayPage - minDisplayPage) + 1;
             // Check if there is a remainder page (partially filled page).
             if ((totalRows % articlesPerPage) != 0) arraySize++;
             // Set array to correct size.
             int[] pages = new int[arraySize];
             // Fill the array.
             for (int i = 1; i <= pages.length; i++) {
                  pages[i - 1] = i;
             // Set pageNext and pagePrev variables.
             if (page != 1) {
                  int pagePrev = page - 1;
                  request.setAttribute("pagePrev", pagePrev);
             if ((totalRows - (articlesPerPage * page)) > 0) {
                 int pageNext = page + 1;
                 request.setAttribute("pageNext", pageNext);
             // These will be used by calling code for SQL query.
             request.setAttribute("startRow", startRow);
             request.setAttribute("endRow", endRow);
             // These will be used in JSP page.
             request.setAttribute("totalRows", totalRows);
             request.setAttribute("numOfPages", numOfPages);
             request.setAttribute("page", page);
             request.setAttribute("pages", pages);          
    }I need two parameters from this method (startrow and endrow) so I can perform my SQL queries. Since this is a multithreaded app, I do not want to use class variables that I will later retrieve through methods.
    So my solution was to just set the two parameters in the request and grab them later with the calling code like this:
    // Set pagination
    Pagination.setPagination(request, conf, tl.getTotalRows());
    // Grab variables set into request by static method
    int startRow = new Integer(request.getAttribute("startRow").toString());
    int endRow = new Integer(request.getAttribute("endRow").toString());
    // Use startRow and endRow for SQL query below...Does anyone see any problem with this from a resource/performance standpoint? Any idea on what the overhead is in using the HttpServletRequest object like this to pass variables around?
    Thanks for any thoughts.

    You could either
    - create instance vars in both controllers and set them accordingly to point to the same object (from the App Delegate) OR
    - create an instance variable on the App Delegate and access it from within the view controllers
    Hope this helps!

  • How to call a static method in a class if I have just the object?

    Hello. I have an abstract class A where I have a static method blah(). I have 2 classes that extend class A called B and C. In both classes I override method blah(). I have an array with objects of type B and C.
    For every instance object of the array, I'm trying to call the static method in the corresponding class. For objects of type B I want to call blah() method in B class and for objects of type C I want to call blah() method in C class. I know it's possible to call a static method with the name of the object, too, but for some reason (?) it calls blah() method in class A if I try this.
    So my question is: how do I code this? I guess I need to cast to the class name and then call the method with the class name, but I couldn't do it. I tried to use getClass() method to get the class name and it works, but I didn't know what to do from here...
    So any help would be appreciated. Thank you.

    As somebody already said, to get the behavior you
    want, make the methods non-static.You all asked me why I need that method to be
    static... I'm not surprised to hear this question
    because I asked all my friends before posting here,
    and all of them asked me this... It's because some
    complicated reasons, I doubt it.
    the application I'm writing is
    quite big...Irrelevant.
    Umm... So what you're saying is there is no way to do
    this with that method being static? The behavior you describe cannot be obtained with only static methods in Java. You'd have to explicitly determine the class and then explicitly call the correct class' method.

  • Using static methods to instantiate an object

    Hi,
    I have a class A which has a static method which instantiates it. If I were to instantiate the class A twice with it's static method within class B then you would think class B would have two instances of class A, right?
    Example:
    class A
       static int i = 0;
       public A(int _i)
           i = _i;
       public static A newA(int _i)
            return new A(_i);
    class B
        public B()
            A.newA(5);
            A.newA(3);
            System.out.println(A.i);
        public static void main(String[] args)
            B b = new B();
    }Is there really two instances of class A or just one? I think it would be the same one because if you check the int i it would be 3 and not 5. Maybe static instantiated objects have the same reference within the JVM as long as you don't reference them yourself?
    -Bruce

    It
    seems like you are the only one having trouble
    understanding the question.Well I was only trying to help. If you don't want any help, its up to you, but if that's the case then I fail to see why you bothered posting in the first place...?
    Allow me to point out the confusing points in your posts:
    you would think class B would have two
    instances of class A, right?The above makes no sense. What do you mean by one class "having" instances of another class? Perhaps you mean that class B holds two static references to instances of Class A, but in your code that is not the case. Can you explain what you mean by this?
    Is there really two instances of class
    A or just one?You have created two instances.
    >I think it would be the same one because if you
    check the int i it would be 3 and not 5.
    I fail to see what that has to do with the number of instances that have been created...?
    Maybe static instantiated objects have the
    same reference within the JVM as long as you
    don't reference them yourself????? What is a "static instantiated object"? If you mean that it was created via some call to a static method, then how is it different to creating an object inside the main method, or any other method that was called by main? (i.e. any method)
    What do you mean by "the same reference within the JVM"? The same as what?
    What happened to the first call "A.newA(5)"?
    I think it was overidden by the second call
    "A.newA(3)".As i already asked, what do you mean by this?
    If you change the line for the constructor
    in A to i = i * i you will get "9" as the
    output, if you delete the call "A.newA(3)"
    you will get "25" as the output. Yes. What part of this is cauing a problem?

  • Non-static method/object cannot be referenced from a static context...?????

    What does this mean. I know about static, but I don't understand why I get this so many times.
    I try to do something pretty normal and this is what I get a lot of times. I mean: the main() method should be static right? Then what good is the main() method if you cannot let it do stuff for you like this:
    public class Test extends JFrame
        public Test
            setSize( 100, 100 );
            show();
    public static main( String args[] )
        Test window = new Test();
        draw();
    public void draw()
        blablabla whatever I want to do, a lot of times I can't.....
    }Why is this, what is the reason for Java to forbid this and what can I do about it?

    Your draw() method, since it isn't defined as static is considered by Java to be part of your Test object; hence, it can only be invoked in the context of an existing instance of your object. In other words, any Java program that wanted to use your draw() method would have to create an instance of your Test class using something likemyTest = new Test()Your main method, however, is something different. Since you want to execute your class as a program, the Java run-time environment needs to have standard starting point. This starting point is the main method. The problem is that the main method must be static, because the run-time environment cannot be expected to know beforehand the correct way to create an instance of your class so that non-static methods can be invoked. The drawback is that your main method can only directly access methods that are defined as static.
    There are two possible solutions to this problem, and which of the two you want to use depends on the object-oriented nature of your program.
    On the one hand, if your draw() method is closely tied to the object itself, if the draw() method is actually drawing your object or a part of it, it should be left as an instance method, and you should simpy use the instance of the object you created in your main method:public static main( String args[] )
        Test window = new Test();
        // maybe some code to generate something to draw???
        window.draw();
    }This is what I think you are trying to do.
    On the other hand, if your draw() method was some kind of universal method that didn't depend in any way on the current configuration of your instance, you could simply define draw() as static at which point your main method (or a method in an external class) could invoke it directly, without a corresponding instance. But if you did that, the draw() method itself would only be able to access static variables and methods.
    Doug

  • Single object referenced by static method

    Hi,
    I have a class, that I know in advance will only be instantiated ONE time. My problem is that I wish to address this object from elsewhere in the programme. I'm using:
    class Client{
    private static Client me = new Client();
    public static Client getMe(){
         return me;
    ....lots of non-static methods
    Is there a better way of doing this (of course there is, but what??)

    Wouldn't have a clue what GoF is, but yes, what you are describing is an honest-to-god, taught to students, pattern.
    It is the accepted way of doing this, you aren't being dodgy (at least not yet).
    Good luck,
    Radish21

  • Static method called from a null object reference

    Hello folks,
    Here´s the code:
    public class TestClass {
         public static void main(String[] args) {
              StaticNull _null_ = null;
              _null_.testNull();
    class StaticNull {
         public static void testNull() {
              System.out.println("testNull");
    }I know that a static method belongs to the class, so you don´t need an
    instantiated object of that class to call it. But in the code above, as
    I'm calling the testNull method from a null reference, shouldn't a NullPointerException
    be thrown?
    Best regards,
    Danniel

    sometimes wrote:
    yawmark wrote:
    Calling static methods from a reference variable should be considered a bad practice. Our coding standards prohibit it, and I suspect we're not the only ones.
    ~what are you trying to say? your coding standard encourages what tricks to invoke static methods? i mean other than using a 'reference variable'?I think you are misreading yawmark's comment. He was saying that invoking a static method using a reference variable -- as though the method weren't static:
    var.staticMethod();...is bad practice. His shop's coding standards prohibit it. And that's a common coding style standard. IDE's often warn you of that, right?
    edit: and judging by your reply #7, you and yawmark would bond over a few jars of cold beverages. You seem think with one mind.

  • Pass an object from a static method

    Hi,
    I'm trying to pass a reference to an object from a static method, but I get an error when compiling.
    Say for example I have this:
    public class obj1 {
    public void myMethod (int i, Object ob, etc...) {
    ...and I want to call this method from a method that looks like this:
    public class obj2 {
    public static int anotherMethod(...) {
    obj1.myMethod(1,this,...);
    ...Can I pass a reference from obj2 to obj1 any other way?
    Thanks alot.

    how can I get a reference to obj2 then?Pay no attention to zdude's answer - it's nonsense.
    You're confused about basic Java concepts. obj2 is a class, not an object. References point to objects, not classes. There is no obj2 object in the code you show, so you cannot have a reference to an obj2 object.
    Maybe if you post some more code, we can get an idea of what you're trying to do. You might want to try the New to Java forum.

  • Simple Question - Data Transfer Object

    Hey gurus,
    I like the option in JBuilder to automatically create Data Transfer Objects and an Assembler for it. But what? I used to make the assembler a Session Bean, and JBuilder makes it a normal Java class with static methods. I know JBuilder always ships with the best solutions, but...
    what is the advantage of the static class here? And in my case, i have the session beans and the entity beans deployed on a different server, would that make a difference for the advantage?
    greets,
    Nick.

    Hey gurus,
    I like the option in JBuilder to automatically create
    Data Transfer Objects and an Assembler for it. But
    what? I used to make the assembler a Session Bean,
    and JBuilder makes it a normal Java class with static
    methods. I know JBuilder always ships with the best
    solutions, but...
    well....... not always
    :-)

  • Exposing Methods of Value Object

    I have the need for a value (transfer) object that contains only getters and setters, as well as a full "business object" that has the same getters and setters as well as business logic (like insert()).
    I hate the idea of maintaining two separate objects, and making sure that when I add a new attribute to the BO I remember to add it to the VO.
    I would love to have the BO hold a private instance of the VO inside it, and automatically "expose" all the VO's methods to the outside world as if they were its own. I could do this with inheritence, but then I have the problem of creating a VO from a BO (lots of error-prone repetitive code).
    Any ideas on how I could expose these methods, together with the BO's logic?
    Thanks, Gary

    If I've understood your question, you may use a Proxy
    object to achieve the desired behaviour.
    What you'll need to do is create a "super" interface
    that contains the methods from your business object
    and value object. You will then create a Proxy that
    implements the "super" interface. When you invoke a
    method on the proxy, the invocation handler will try
    to first invoke the method on the business object. If
    the business object does not implement the requested
    method (i.e. one of the value methods), the handler
    tries to invoke the method on the value object member
    of the business object.
    The only maintainence overhead implied by this
    solution is that methods must be added to the "super"
    interface to correspond to each method added to the
    business or value objects.
    Have a look at this example to see what I mean
    public class Test {
    public static void main(String[] args) {
    try {
    ProxyHandler d = new ProxyHandler(new
    Handler(new BusinessObject());
    Object o =
    Object o =
    Proxy.newProxyInstance(Thread.currentThread().getConte
    tClassLoader(),
    new Class[]
    new Class[] {BusinessValueInterface.class},
    class}, d);
    BusinessValueInterface bvi =
    rface bvi = (BusinessValueInterface)o;
    bvi.businessMethod();
    System.out.println(bvi.getVal());
    catch (Exception ex) {
    ex.printStackTrace();
    static class ProxyHandler implements
    nts InvocationHandler {
    BusinessObject b;
    public ProxyHandler(BusinessObject bo) {
    b = bo;
    public Object invoke(Object proxy, Method m,
    thod m, Object[] params)
    throws Throwable
    Class[] paramClasses = null;
    if (params != null) {
    paramClasses = new
    amClasses = new Class[params.length];
    for (int x = 0; x < params.length;
    params.length; x++)
    paramClasses[x] =
    paramClasses[x] = params[x].getClass();
    Method m1 = null;
    try {
    m1 =
    m1 = b.getClass().getMethod(m.getName(),
    getName(), paramClasses);
    catch (Exception ex) {
    if (m1 != null) {
    return m1.invoke(b, params);
    else {
    Method m2 =
    Method m2 =
    2 = b.val.getClass().getMethod(m.getName(),
    paramClasses);
    if (m2 != null) {
    return m2.invoke(b.val, params);
    else {
    return null;
    interface BusinessValueInterface {
    public String getVal();
    public void businessMethod();
    static class BusinessObject {
    ValueObject val = new ValueObject();
    public void businessMethod() {
    System.out.println("businessMethod
    inessMethod invoked");
    static class ValueObject {
    public String getVal() {
    return "value";
    Good luck,
    MikeI would definetly like to know more about what performance characteristics is needed in the system before recommending a dynamic proxy. Value objects accessors and mutators tend to be the most called methods in a system, and there is a fairly large overhead for dynamic proxies (about 5*(normal method call) on a windows 2000 box running IBM jre 1.3.1). Dynamix proxies are great and I use them for a lot of things, but NOT for value object setter and getters...
    I�d recommend either wrapping the VO in the BO and exposing it as:
    MyBO myBo = getBO();
    myBo.getValue().setName( ... ); or make the BO stateless and pass the value in the method calls:
    myBO.performSomeNiceBusinessLogic( valueObject, someOtherArgument );The latter is probably the way I would go for most cases, but the former has its advantages to.
    Br - johan

Maybe you are looking for

  • Sample Response File for Oracle Database 12c Standard Edition on Oracle Linux 6.4 -- working

    oracle@styles-and-artists-development-oracle database]$ cat response/db_install.rsp ## Copyright(c) Oracle Corporation 1998,2013. All rights reserved.## ## Specify values for the variables listed below to customize     ## ## your installation.       

  • Video playback stops and starts

    I've never had this problem before but since I wiped my 5th Gen (late 2006) iPod Video and put new content on it the video playback keeps freezing for a second and then continuing. Most of the time the audio keeps going but sometimes they both stop a

  • After rendering, no sound

    After rendering a 30 min clip with neat video, warp stabilizer and other small changes, there is no sound once video been produced by encoder. I also find that sequence  won't even render on timeline but I do have sound. What is the problem? Thanks N

  • AppleWorks quits when I try to spellcheck

    I am running 10.2.8 on my mac. I have Appleworks 6.0.4. After typing in a document it and try to spellcheck it simply quits. What do you suggest?

  • Adobe on N73

    Anyone come across this problem. Adobe on my N73 will not load. Cannot find a way of reinstalling it so am stuck. Anyone know hjow to fix this? Thanks