Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / June 2006

Tip: Looking for answers? Try searching our database.

Newbie trouble

Thread view: 
Schlum - 15 Jun 2006 16:48 GMT
Hi,

I am a beginner in Java and I have the following trouble:

I have a class A with 2 methods: setThis and setThat
I want to write something like this:

String myVar = String("setThis");
A.myVar("hello World");

I am looking in google for an answer for one hour, but I don't know how
to express what I wanna do...
Anyone got the answer ?

Regards,
Schlum
KingNarg - 15 Jun 2006 17:17 GMT
Try this:

public class A {
   
    private String myVar;
   
    public String getMyVar() {
        return myVar;
    }

    public void setMyVar(String s) {
        myVar = s;
    }   
}

public class test {

    public static void main(String[] args) {
        A a = new A();
        a.setMyVar("Hello World");
        System.out.println(a.getMyVar());
    }
}

Best Regards
Narg
Oliver Wong - 15 Jun 2006 17:17 GMT
> Hi,
>
[quoted text clipped - 9 lines]
> express what I wanna do...
> Anyone got the answer ?

   It's not clear what you want to do, nor what the problem is. Are you
getting a compile error? A runtime error? Something else? You might want to
read
http://riters.com/JINX/index.cgi/Suggestions_20for_20Asking_20Questions_20on_20N
ewsgroups


   - Oliver
Tim Slattery - 15 Jun 2006 17:18 GMT
>Hi,
>
[quoted text clipped - 9 lines]
>to express what I wanna do...
>Anyone got the answer ?

I can't tell what you're trying to do. You're not using either of the
methods in class A. You create a string named myVar, and set its value
to the string "setThis". BTW: The correct syntax for this would be:

String myVar = new String("setThis");

Then you invoke a method of A that either doesn't exist or that you
didn't tell us about, A.myVar. You haven't instantiated an object of
type A so I guess that method must be static. If it exists.

What are you trying to do?

--  
Tim Slattery
Slattery_T@bls.gov
ItchyNadirTongue - 15 Jun 2006 17:29 GMT
Schlum,

I am not 100% clear what you are trying to accomplish but it looks like
you want to invoke a method (A.setThis) just by using the String name
of that method ("setThis").  Since Java is strongly-typed, this sort of
syntax is not permitted.  It is possible to achieve this by using
reflection.  For example the JavaBeans framework and the Jakarta
Commons BeanUtils project are all about this sort of task.

If you used the commons-beanutils.jar library from Jakarta Commons, you
could just do the following:

A a = new A();
org.apache.commons.beanutils.PropertyUtils.PropertyUtils.setSimpleProperty(a,
"this", "hello world");

If you wanted to accomplish this task using the raw reflection API from
the java.beans and java.lang.reflect packages, this will take a little
bit more work.

           BeanInfo beanInfo = Introspector.getBeanInfo(A.class);
           PropertyDescriptor[] props =
beanInfo.getPropertyDescriptors();
           for (int i = 0; i < props.length; i++) {
               PropertyDescriptor prop = props[i];
               if (prop.getName().equals("this")) {
                   Method setThis = prop.getWriteMethod();
                   setThis.invoke(info, new Object[] { "hello world" }
);
               }
           }

The following is a variation of the above which highlights the
distinction between a "method" and a property:

           BeanInfo beanInfo = Introspector.getBeanInfo(A.class);
           MethodDescriptor[] methods =
beanInfo.getMethodDescriptors();
           for (int i = 0; i < methods.length; i++) {
               MethodDescriptor method = methods[i];
               if (method.getName().equals("setThis")) {
                   method.getMethod().invoke(info, new Object[]{"hello
world"});
                   break;
               }
           }

As you can see from both these examples, you have to get a handle to
the java.lang.reflect.Method object in order to invoke "setThis" in a
dynamic manner.   It is obviously complicated, but Java does not offer
any "syntatic sugar" to simplify.



Does this response address your question?
Schlum - 15 Jun 2006 17:37 GMT
> Schlum,
>
[quoted text clipped - 51 lines]
>
> Does this response address your question?

Yess ! That is exactly what I was trying to do.
I am surprise it is so long to do this, it surely means that my way to
code is not the best one ... I thought I had a good idea to avoid
writing 12 methods to instantiate my class :)

Thanks a lot,
Schlum
Patricia Shanahan - 15 Jun 2006 20:14 GMT
...
>> Does this response address your question?
>>
> Yess ! That is exactly what I was trying to do.
> I am surprise it is so long to do this, it surely means that my way to
> code is not the best one ... I thought I had a good idea to avoid
> writing 12 methods to instantiate my class :)
...

Almost every time I've considered reflection I've found a much simpler,
cleaner solution to the problem.

Can you explain a bit about why your class would require 12 methods for
instantiation? There may be an easier way of doing it.

Patricia
Schlum - 16 Jun 2006 03:44 GMT
> ...
>>> Does this response address your question?
[quoted text clipped - 12 lines]
>
> Patricia
Definitely I was really tired when I tried to do this.
There is no need for reflection, and no needs neither for 12 methods for
instantiation...

Thanks a bunch for your help,
Schlum
Schlum - 15 Jun 2006 17:32 GMT
Sorry, my question was not clear enough

I try to do the following.

Class A {

    String param1
    String param2
    String param3

    A(HashMap initHash){
    // This Hash can contain one or two or the three param
    // I make a keySet and an Iterator on this keyset
    // I would like to be able to init the param passed
    // through the hash.
    paramsPassedIterator = initHash.keySet().Iterator()
    while(paramsPassedIterator.hasNext()){
        // this is the part I am lost...
        A.set_paramsPassedIterator.next()(iniHash.get())
        }

    }

}

> Hi,
>
[quoted text clipped - 12 lines]
> Regards,
> Schlum
ItchyNadirTongue - 15 Jun 2006 17:43 GMT
I recommend using Jakarta Commons BeanUtils package for this sort of
task.  For example, the BeanUtils.populate() method was designed to
populate a JavaBean based on the values  in a Map.

package com.milleypopp.test;

import java.util.HashMap;

public class A {

   private String param1;
   private String param2;
   private String param3;

   public A(HashMap initHash) throws Exception {
       org.apache.commons.beanutils.BeanUtils.populate(this,
initHash);
   }

   public String getParam1() {
       return param1;
   }

   public void setParam1(String param1) {
       this.param1 = param1;
   }

   public String getParam2() {
       return param2;
   }

   public void setParam2(String param2) {
       this.param2 = param2;
   }

   public String getParam3() {
       return param3;
   }

   public void setParam3(String param3) {
       this.param3 = param3;
   }

   public static void main(String[] args) {
       try {
           HashMap map = new HashMap();
           map.put("param1", "hello");
           map.put("param2", "world");
           A a = new A(map);

       }
       catch (Exception e) {
           e.printStackTrace();
       }
   }
ItchyNadirTongue - 15 Jun 2006 17:51 GMT
I did not offer comment on your coding style.  In general, you want the
compiler to catch errors for you.  If you do fancy stuff with
reflection like this, then you are undermining a standard programming
maxim:  "Prefer compiler-time errors to runtime errors."

Also, I wouldnt use reflection just because you dont like having "big
classes" with lots of getter and setter methods.  You should be using
an IDE which generates getter and setter methods for you, so it
shouldnt take up any significant typing time.

To summarize:  dont use reflection, unless you have a good reason for
doing it.  Web frameworks such as Struts are completely built using
JavaBeans-style reflection.   This makes it simple to build web pages,
but admittedly you tend to get more runtime errors when using Struts as
a result.


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.