CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 8 of 8

Threaded View

  1. #1
    Join Date
    Jul 2005
    Location
    Currently in Mexico City
    Posts
    568

    Question about inheritance in Java

    I am writing a small bean manager and I was wondering if it is possible to extend Object class to make new methods apply to my beans without having each bean implement my extended class.

    for example I have a fieldset copying method which scans source and target beans for similar fields and types and copies values from one bean to the other:
    Code:
    public static Object map(Object beanA, Object beanB) {
      Class<?> classA = beanA.getClass();
      Class<?> classB = beanB.getClass();
      Field[] fieldsetA = classA.getDeclaredFields();
      Field[] fieldsetB = classB.getDeclaredFields();
      try {
        for (Field fieldA : fieldsetA) {
          for (Field fieldB : fieldsetB) {
            if (fieldA.getName().equals(fieldB.getName()) && fieldA.getType() == fieldB.getType()) {
              String setterName = "set" + capitalize(fieldB.getName());
              String getterName = (fieldA.getType().getName().equals("boolean") ? "is" : "get") + capitalize(fieldA.getName());
              Method getter = classA.getDeclaredMethod(getterName);
              Method setter = classB.getDeclaredMethod(setterName, fieldB.getType());
              setter.invoke(beanB, getter.invoke(beanA));
            }
          }
        }
      } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace(System.out);
      }
      return beanB;
    }
    So later I use:
    Code:
    beanB = (BeanB)map(beanA,beanB);
    It works. Still what I would like is to be able to apply map method to a bean2 object directly without needs of casting and mentioning bean2 twice. Something like this:
    Code:
    beanB.map(beanA);
    Is it possible without implementing my extended class in every bean explicitly? Or have I recompile the JDK Object class and use my own JDK distro?
    Last edited by Xeel; October 7th, 2009 at 04:46 PM.
    Wanna install linux on a vacuum cleaner. Could anyone tell me which distro sucks better?

    I had a nightmare last night. I was dreaming that I’m 64-bit and my blanket is 32-bit and I couldn’t cover myself with it, so I’ve spent the whole night freezing. And in the morning I find that my blanket just had fallen off the bed. =S (from: bash.org.ru)

    //always looking for job opportunities in AU/NZ/US/CA/Europe :P
    willCodeForFood(Arrays.asList("Java","PHP","C++","bash","Assembler","XML","XHTML","CSS","JS","PL/SQL"));

    USE [code] TAGS! Read this FAQ if you are new here. If this post was helpful, please rate it!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured