Results 1 to 17 of 17
  1. #1
    jon80's Avatar
    jon80 is offline Senior Member
    Join Date
    Feb 2008
    Location
    Malta (EU)
    Posts
    211
    Rep Power
    7

    Default [newbie] getting class members from Arraylist

    I'm trying to retrieve the methods of classes from objects stored within an Arraylist, is this possible?

    :confused:

    Java Code:
    Employee[] staff = new Employee[3];
    
    ...
    
    ArrayList newStaff = new ArrayList();
    		
    		//fill newStaff
    		
    		for (Integer i = 0; i < staff.length; i++)
    		{
    			newStaff.add(staff[i]);
    		}
    		
    		//display newStaff
    		for (Integer i = 0; i < staff.length; i++)
    		{
    			System.out.println(newStaff.get(i).getClass().getName());
                            //hmm?
    		}
    Output:
    //name of the class; I need the methods
    homenetwork.bkr.training.Employee
    homenetwork.bkr.training.Employee
    homenetwork.bkr.training.Employee

  2. #2
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    11,825
    Rep Power
    19

    Default

    Quote Originally Posted by jon80 View Post
    I'm trying to retrieve the methods of classes from objects stored within an Arraylist, is this possible?

    :confused:

    Java Code:
    Employee[] staff = new Employee[3];
    
    ...
    
    ArrayList newStaff = new ArrayList();
    		
    		//fill newStaff
    		
    		for (Integer i = 0; i < staff.length; i++)
    		{
    			newStaff.add(staff[i]);
    		}
    		
    		//display newStaff
    		for (Integer i = 0; i < staff.length; i++)
    		{
    			System.out.println(newStaff.get(i).getClass().getName());
                            //hmm?
    		}
    Output:
    //name of the class; I need the methods
    homenetwork.bkr.training.Employee
    homenetwork.bkr.training.Employee
    homenetwork.bkr.training.Employee
    Well, you've already got the Class (through getClass())...so have a look at the API for that and see if you can spot a useable method...hint, it's called pretty much exactly what you'd expect it to be called.
    :)

  3. #3
    jon80's Avatar
    jon80 is offline Senior Member
    Join Date
    Feb 2008
    Location
    Malta (EU)
    Posts
    211
    Rep Power
    7

    Default

    I looked but I didn't find anything useful...that is why I ask for help.

    I tried experimenting with the .getClass.getField and getClass.getDeclaredField, but still no joy.

    API is not too clear for dummies like myself either :)

  4. #4
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    11,825
    Rep Power
    19

    Default

    Quote Originally Posted by jon80 View Post
    I looked but I didn't find anything useful...that is why I ask for help.

    I tried experimenting with the .getClass.getField and getClass.getDeclaredField, but still no joy.

    API is not too clear for dummies like myself either :)
    Well, you said what you were looking for yourself...methods...not fields.

    So, instead of getFields you'd use ...

    (Sorry for being cryptic, but it does help...honestly)

  5. #5
    jon80's Avatar
    jon80 is offline Senior Member
    Join Date
    Feb 2008
    Location
    Malta (EU)
    Posts
    211
    Rep Power
    7

    Default

    That's fine, I'll dig further. Thanks for your help.

  6. #6
    jon80's Avatar
    jon80 is offline Senior Member
    Join Date
    Feb 2008
    Location
    Malta (EU)
    Posts
    211
    Rep Power
    7

    Default

    I'm trying to use the following code to read the methods of the underlying class,but I am getting the methods of java.util.ArrayList instead.

    ?

    Java Code:
    package homenetwork.bkr.training;
    
    import java.util.ArrayList;
    import java.lang.reflect.*;
    
    public class EmployeeTest {
    
    	public static void main(String[] args) {
    		
    		//1. create an array and create new employees
    		Employee[] staff = new Employee[3];
    		
    		staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15);
    		staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
    		staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);
    		
    		ArrayList newStaff = new ArrayList();
    		//2a. store array staff in an ArrayList
    		for (Integer i = 0; i < staff.length; i++)
    		{
    			newStaff.add(staff[i]);
    		}
    		
    		/* Does not work because staff is an Employee object not a collection.
    			newStaff.addAll((Collection) staff);
    		*/
    		
    		//1. read the methods into _methods
    		Method[] _methods = newStaff.getClass().getMethods();
    //erm?
    		
    		//2. run the Employee.Name() method ??
    //for ... ??
    	}
    
    }
    Last edited by jon80; 05-13-2009 at 04:05 PM.

  7. #7
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    11,825
    Rep Power
    19

    Default

    Quote Originally Posted by jon80 View Post
    I'm trying to use the following code to read the methods of the underlying class,but I am getting the methods of java.util.ArrayList instead.

    ?
    Knew you'd find the right method...:)

    Java Code:
    		
    		ArrayList newStaff = new ArrayList();
    ...
    		Method[] _methods = newStaff.getClass().getMethods();
    Right, you've called getClass on ArrayList, so the subsequent getMethods is on the ArrayList class...so you get those methods.

    If you want the methods of something contained within the ArrayList you'll have to get one of the items out first, then do the getClass().getMethods() call on that.

    ETA: Or, just use one the Employee objects you already have...
    Last edited by Tolls; 05-13-2009 at 04:26 PM.

  8. #8
    jon80's Avatar
    jon80 is offline Senior Member
    Join Date
    Feb 2008
    Location
    Malta (EU)
    Posts
    211
    Rep Power
    7

    Default

    Thanks, well the output of:

    Java Code:
    for (Integer i = 0; i < _methods.length; i++)
    		{
    			System.out.println(_methods[i].toString());
    		}
    ...seems to list the methods of the ArrayList, which is not what I am expecting, since I wanted the methods of the Employee class.

    To be honest I wanted to create a code "template" with ArrayLists, since they are convenient to use :)

    See http://javabeanz.wordpress.com/2007/...ce-tips-part-1 (although I'm sure you would be aware of these issues).

    NOTE: It would be nice to have the possibilty to use <a href> </a> tags for typing in links etc.

    public boolean java.util.ArrayList.add(java.lang.Object)
    public void java.util.ArrayList.add(int,java.lang.Object)
    public java.lang.Object java.util.ArrayList.get(int)
    public java.lang.Object java.util.ArrayList.clone()
    public int java.util.ArrayList.indexOf(java.lang.Object)
    public void java.util.ArrayList.clear()
    public boolean java.util.ArrayList.contains(java.lang.Object)
    public boolean java.util.ArrayList.isEmpty()
    public int java.util.ArrayList.lastIndexOf(java.lang.Object)
    public boolean java.util.ArrayList.addAll(int,java.util.Collectio n)
    public boolean java.util.ArrayList.addAll(java.util.Collection)
    public int java.util.ArrayList.size()
    public java.lang.Object[] java.util.ArrayList.toArray(java.lang.Object[])
    public java.lang.Object[] java.util.ArrayList.toArray()
    public boolean java.util.ArrayList.remove(java.lang.Object)
    public java.lang.Object java.util.ArrayList.remove(int)
    public java.lang.Object java.util.ArrayList.set(int,java.lang.Object)
    public void java.util.ArrayList.ensureCapacity(int)
    public void java.util.ArrayList.trimToSize()
    public int java.util.AbstractList.hashCode()
    public boolean java.util.AbstractList.equals(java.lang.Object)
    public java.util.Iterator java.util.AbstractList.iterator()
    public java.util.List java.util.AbstractList.subList(int,int)
    public java.util.ListIterator java.util.AbstractList.listIterator(int)
    public java.util.ListIterator java.util.AbstractList.listIterator()
    public java.lang.String java.util.AbstractCollection.toString()
    public boolean java.util.AbstractCollection.containsAll(java.util .Collection)
    public boolean java.util.AbstractCollection.removeAll(java.util.C ollection)
    public boolean java.util.AbstractCollection.retainAll(java.util.C ollection)
    public final void java.lang.Object.wait() throws java.lang.InterruptedException
    public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
    public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
    public final native java.lang.Class java.lang.Object.getClass()
    public final native void java.lang.Object.notify()
    public final native void java.lang.Object.notifyAll()
    Last edited by jon80; 05-13-2009 at 05:04 PM.

  9. #9
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    Well, as Tolls said, you need to retrieve the object from the ArrayList, and THEN call the methods on it. So, the line to retrieve the methods should be
    Java Code:
    /*0 can be replaced with the index of whichever object you want*/
    Method[] _methods = newStaff.get(0)getClass().getMethods();
    BTW: ArrayList should be parameterized because it uses Generics, so your declaration should be
    Java Code:
    ArrayList<Employee> newStaff = new ArrayList<Employee>();
    //Instead of ArrayList newStaff = new ArrayList();
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  10. #10
    jon80's Avatar
    jon80 is offline Senior Member
    Join Date
    Feb 2008
    Location
    Malta (EU)
    Posts
    211
    Rep Power
    7

    Default

    lol, well I started reading a book about Java to grasp the basics, coz I like programming languages; I'm more familiar with .NET namespaces, but the idea of "write once, deploy anywhere" is the motivating part; besides Visual Studio 2008 / ASP.NET on .NET 3.5 has a few unpleasant easter eggs that the books don't always mention :)

    The procedure now lists all the methods including those that pertain to "java.lang.Object.*". I tried blocking them out with some code unsuccessfully:

    Java Code:
    ...
    final String _PACKAGENAME = "package homenetwork.bkr.training";
    ...
    
    if(newStaff.get(i).getClass().getPackage().toString().trim().equals(_PACKAGENAME))
     _methods = newStaff.get(i).getClass().getMethods();
    
    //NOTE does not work, excuse the repetition. I also tried using ..startsWith() at the end to no avail.
    
    ...
    if (newStaff.get(0).getClass().getPackage().toString().trim().startsWith(_PACKAGENAME))
    _methods = newStaff.get(i).getClass().getMethods();
    ...
    1. I still have to find a way to call this dynamically, but in any case it is not working atm.



    2. Why should I parameterize the Arraylist to be bound to a specific object, when it works fine as a Generic? I did update the code of course and it works fine just the same.


    3. Any idea how to call any of these methods?

  11. #11
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    Why parameterize the ArrayList? So that if you ever go back to your code, you A: know exactly what it stores just by looking at the declaration. And B: You can't go brain-dead at some point and to add the wrong type of Object to the ArrayList. Also means that you don't have to use casts on the get() methods. As a final bonus, you won't get compiler errors, and it's a good habit to have.

    As for retrieving only the methods declared by the Employee class, just use getDeclaredMethods(). It will not return inherited methods, only the methods defined by the class.

    If by calling it dynamically, you mean calling it from other code without writing it out again, just create a method that prints out what you want.
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  12. #12
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    I'm curious why you are doing this? What's the story behind the story? Why this particular assignment?

  13. #13
    jon80's Avatar
    jon80 is offline Senior Member
    Join Date
    Feb 2008
    Location
    Malta (EU)
    Posts
    211
    Rep Power
    7

    Default lol

    training...

  14. #14
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    training...
    You'll likely get a lot more out of reviewing more of the basics of Java than this exercise in Reflection, something that if you think you need to use in your program at this point, you probably don't (with 99.99% certainty, trust me).
    Last edited by Fubarable; 05-14-2009 at 11:20 PM.

  15. #15
    jon80's Avatar
    jon80 is offline Senior Member
    Join Date
    Feb 2008
    Location
    Malta (EU)
    Posts
    211
    Rep Power
    7

    Default

    Thanks. The documentation is a bit hard to read mostly coz there's lots of room for "check yourself", and, incomplete examples.

    I would like to learn more on development for mobile phones and J2EE (for applications with the concept of thin clients) eventually.

    (haven't yet decided which, but who says I have to choose :)

  16. #16
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    So... you figured it out yet? And yes, java.lang.reflect is one of those rather useless packages in Java that are there only because it is very difficult to implement it yourself.

    Let me know if you need more help :D
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  17. #17
    jon80's Avatar
    jon80 is offline Senior Member
    Join Date
    Feb 2008
    Location
    Malta (EU)
    Posts
    211
    Rep Power
    7

    Default

    Not really I'm stuck asking myself why the .contains does not seem to work.

    Then I have to figure out how to run the methods I want :)

    Java Code:
    ....
    Method[] _methods = null;
    		ArrayList <String> _methodsFilter1 = new ArrayList<String>();
    		final String _PACKAGENAME = "homenetwork.bkr.training";  //TODO retrieve dynamically
    		
    		final short _MAX_METHODS_TO_RUN = 2;
    		final String[] _methodsToRun = new String[_MAX_METHODS_TO_RUN];
    		
    		_methodsToRun[0] = "Salary()"; //FIX: Declaration does not work 
    		_methodsToRun[1] = "Name()"; //FIX: Declaration does not work
    		
    		//if (debug) System.out.println("DEBUG :" + _methodsToRun[0]);
    		//if (debug) System.out.println("DEBUG :" + _methodsToRun[1]);
    
    		//1. Get the methods from employee
    		_methods = Employee.class.getMethods();
    		for (Method _m : _methods)
    		{
    		if (debug) {System.out.println("DEBUG (1.1) - before checking for package name:" + _m.toString());}
    			
    			if ((_m.toString().contains(_PACKAGENAME))  && 
    					(_m.toString().contains(_methodsToRun[0])) &&     //FIX...doesn't evaluate to true
    							(_m.toString().contains(_methodsToRun[1]))) //FIX...doesn't evaluate to true
    			{	
    				if (debug) {
    						System.out.println("DEBUG (1.2) - after checking for package name:" + _m.toString());
    						System.out.println("DEBUG (1.3) - after checking for package name:" + _methodsToRun[0]);
    						System.out.println("DEBUG (1.4) - after checking for package name:" + _methodsToRun[1]);
    					}
    			}
    		}
    		
    		//2. Run the methods which I require
    ....

Similar Threads

  1. Newbie - Robot Class
    By drasgear in forum New To Java
    Replies: 2
    Last Post: 11-14-2008, 04:46 PM
  2. [SOLVED] is final class members are also final ?
    By haoberoi in forum New To Java
    Replies: 4
    Last Post: 11-10-2008, 03:01 PM
  3. Newbie help with ArrayList!
    By oldmanhouse in forum New To Java
    Replies: 2
    Last Post: 11-05-2008, 11:46 PM
  4. Doclet that prints out all members of the class
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-16-2008, 11:06 PM
  5. Help passing arraylist to another class
    By adlb1300 in forum New To Java
    Replies: 3
    Last Post: 11-06-2007, 08:02 PM

Posting Permissions

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