LinuxQuestions.org
Share your knowledge at the LQ Wiki.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 12-21-2007, 05:32 PM   #1
manolakis
Member
 
Registered: Nov 2006
Distribution: xubuntu
Posts: 464

Rep: Reputation: 37
[] getClasses() Java


Hi there

I actually want to use the [] getClass() method and then with a for loop to call the default contructor of each class that belongs to the returned array. Any ideas how can I do that?

Thanks
 
Old 12-22-2007, 04:51 AM   #2
Alien_Hominid
Senior Member
 
Registered: Oct 2005
Location: Lithuania
Distribution: Hybrid
Posts: 2,247

Rep: Reputation: 53
Self modifying code possibly.
 
Old 12-22-2007, 05:47 AM   #3
jay73
LQ Guru
 
Registered: Nov 2006
Location: Belgium
Distribution: Ubuntu 11.04, Debian testing
Posts: 5,019

Rep: Reputation: 133Reputation: 133
Maybe this would make a nice case of polymorphism.

For example, I have a base class:

class Animal{}

And I have three more that inherit from Animal

class Dog extends Animal{}

class Cat extends Animal{}

class Duck extends Animal{}

Then I can make an Array like this:

Animal [] farm = {new Dog(), new Cat(), new Duck()};

Now if I print all the elements in the array:

for (Animal animal : farm)
System.out.println(animal.getClass());

then each element will effectively be of its own specific type rather than of the base class type, i.e. Dog, Cat and Duck respectively.
 
Old 12-22-2007, 06:13 AM   #4
Alien_Hominid
Senior Member
 
Registered: Oct 2005
Location: Lithuania
Distribution: Hybrid
Posts: 2,247

Rep: Reputation: 53
I thought he needed smth similar to this.
Code:
if (farm[0].getClass() == "dog") new dog(); // if we got cat, then new cat()
 
Old 12-22-2007, 06:45 AM   #5
manolakis
Member
 
Registered: Nov 2006
Distribution: xubuntu
Posts: 464

Original Poster
Rep: Reputation: 37
Hi there

I would like to thank you for your examples. I found them really useful.
There is only a last thing that I want to know. I want to use the following command.
Quote:
Constructor[] getConstructors()
For instance, with your example, should look like this:
Quote:
Constuctor [] constr = farm[2].getConstructors();
Lets say that farm[2] has got a number of different constructors, including a copy constructor. Setting the case that we need to implement a factory method like http://en.wikipedia.org/wiki/Factory_method_pattern, and for a greater convenience we want to use a copy constructor so to "easily" copy the object. An example could be:
Quote:
Animal factoryMethod(Animal animal)
{
// assuming that it is a Duck
return new Duck((Duck) animal);
}
My actual question is how to look in the constr[] for the appropriate copy constructor. I don't know if Java has a special method but this as I can imagine should be done with if-statements, possibly in the same way as Alien_Hominid suggested with the class method. Once more again I would be really obliged for your help, and your advice.

Thanks in advance
manolakis
 
Old 12-22-2007, 07:12 AM   #6
jay73
LQ Guru
 
Registered: Nov 2006
Location: Belgium
Distribution: Ubuntu 11.04, Debian testing
Posts: 5,019

Rep: Reputation: 133Reputation: 133
I'm afraid that I'm somewhat confused. What do you mean, look for the right constructor? If your class was properly written, the right constructor should automatically get selected depending on the argument used to create the new instance. You can't have two constructors that take the same type and number of arguments (say, Animal or Duck) as it would immediately get flagged as an error.
 
Old 12-22-2007, 01:32 PM   #7
Alien_Hominid
Senior Member
 
Registered: Oct 2005
Location: Lithuania
Distribution: Hybrid
Posts: 2,247

Rep: Reputation: 53
Mine example won't work. It was an example, not a working code. You need to call Class.toString() method, to get class name.

What I was really meaning talking about self modifying code is this:

1) enter class name(s), which you want to load
2) read class name(s) into variable/array
3) I don't know how to create objects from input variables dynamically (if somebody knows, please elaborate) so you probably need to have a prepared template file, edit it using java i/o functions and insert the name(s) from variable/array into proper location
4) call javac and java to execute the new class

/\
||
never tried this

You can't have identically defined constructors in the same class.

Last edited by Alien_Hominid; 12-22-2007 at 01:35 PM.
 
Old 12-22-2007, 05:09 PM   #8
Looking_Lost
Senior Member
 
Registered: Apr 2003
Location: Eire
Distribution: Slackware 12.0, OpenSuse 10.3
Posts: 1,120

Rep: Reputation: 45
Not quite sure what you want to do but interesting enough, anyway, you can get information about an objects constructors, and "Constructor" has an "newInstance" method that might be of use to you. Either way won't do any harm to have a look up on reflection.

Code:
import java.lang.reflect.Constructor;
import java.lang.reflect.Member;


class Test{

public static void main(String args[]) {

    try{
        

        Object[] objArray=new Object[]{new String(), new Integer(1), new Boolean(true), new Float(1.0)};

        for(Object obj: objArray){

            Class<?> c=Class.forName(obj.getClass().getName());
        
            Member[] members=c.getConstructors();
        
            Constructor con;
        
            for (Member mbr : members) {
        
                System.out.print( ((Constructor)mbr).toGenericString());
                   Class<?>[] types=((Constructor)mbr).getParameterTypes();
        
                if(types.length==0){
                
                    System.out.print(" EMPTY CONSTRUCTOR ");
                
                }else
                         if(types.length==1 && (types[0].getName().equals(c.getName()))){

                    System.out.print(" 'COPY CONSTRUCTOR' "); //Won't be picked out for Integer,
                                          //Boolean and Float as they are wrappers for int,
                                          //boolean and float
                }
            
             System.out.println();
            }
    }

    }catch(Exception e){ //Very lazy catch
        System.err.println(e.getMessage());
    }
    }

}
 
Old 12-23-2007, 10:10 AM   #9
manolakis
Member
 
Registered: Nov 2006
Distribution: xubuntu
Posts: 464

Original Poster
Rep: Reputation: 37
Dear Looking Lost

I have to say that your code is exactly what I was looking for. I haven't yet tested but I am convinced that will work perfectly for my case. I would be happy if you can explain me one thing that I haven't been familiar enough in my life, especially from a Java practical implementation point of view.

Quote:
Class<?> c=Class.forName(obj.getClass().getName());
Can you with view words explain me why Class<?> ? How can templates be used for polymorphism? Can we modify jay73's example in the following form, and if yes what will be the profit?
Quote:
template <Animal>{}

template <Dog> extends <Animal>{}

template <Cat> extends <Animal>{}

template <Duck> extends <Animal>{}
I have never written a Java code using templates so excuse me if my quote is not correct.

Thanks for your code
Manolakis
 
Old 12-23-2007, 05:45 PM   #10
Looking_Lost
Senior Member
 
Registered: Apr 2003
Location: Eire
Distribution: Slackware 12.0, OpenSuse 10.3
Posts: 1,120

Rep: Reputation: 45
I can only refer you to the Sun java documentation which I assume the other folks are famiiar with and would not pretend to give a better explanation of. Come on lad, are you a c++ programmer?.
 
Old 12-24-2007, 07:47 PM   #11
paulsm4
LQ Guru
 
Registered: Mar 2004
Distribution: SusE 8.2
Posts: 5,863
Blog Entries: 1

Rep: Reputation: Disabled
Querying "what kind of class" is often appropriate ...
... but it's also very often a symptom of poor design.

When you stop to think about it, one of the main reasons for using "objects" in the first place is to *hide* as much information as possible.

The better strategy is to structure your code so that you need to know *less* about the object (which tends to make your code simpler and more flexible), rather than make "if/else" or "switch/case" decisions based on type.

IMHO .. PSM

PS:
Excellent book reference:

Thinking in Java, Bruce Eckel
http://mindview.net/Books/TIJ/
<= The current, 4th edition is reasonably priced at $25.00
The previous, 3rd edition, is completely free
*Both* are *excellent* overviews of Java programming and OO design
 
Old 12-27-2007, 07:36 AM   #12
manolakis
Member
 
Registered: Nov 2006
Distribution: xubuntu
Posts: 464

Original Poster
Rep: Reputation: 37
Looking_Lost,

I would like once more again your precious help.
Lets say that there is an object A like:

Quote:
public class A
{
private String asString;
private char asChar;
private int asInt;

public A(String asString, char asChar, int asInt)
{
this.asString;
this.asChar=asChar;
this.asInt=asInt;
}

public A(String asString, char asChar)
{
this.asString;
this.asChar=asChar;
}

public A()
{
asString="A";
asChar='A';
asInt=1;
}

public A(A copy)
{
// Here comes my question
}
}
I am actually wondering how can I copy in a copy-constructor every instance of A, in particular , asString, asChar, asInt, with-out copying null values (like for example the asInt in A(String,Char)) . I would like if you have once more again the kindness to give me an example like in your second post. Imagine that there could be an object with hundred of instances that some of them in an instantiation could be null, and that you don't want implicitly copy every value. What I really dont want to do is the following:
Quote:
public class hundInstObject
{
private String firstInstance;
private String secondInstance;
// ...upto hundred

public hundInstObject(hundInstObject copy)
{
if(firstInstance!=null)
firstInstance = copy.firstInstance;
if(secondInstance!=null)
secondInstance = copy.secondInstance;
// How can I copy all the hundred in a way much more like you did with
// the copy constructors in your second post? Also imagine that instances
// of an object could be of different types
}
}
Really don't know how to thank you
Manolakis
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
Java plugin installed correctly for Firefox but not able to view any java applet tvn Linux - Software 10 04-15-2010 02:13 AM
LXer: Java Look-Alike Project Pushed Sun To Make Java Open Source LXer Syndicated Linux News 0 11-15-2006 03:54 AM
LXer: Java news met with cautious optimism in free Java community LXer Syndicated Linux News 0 11-14-2006 10:21 PM
Firefox refuses to load Java jnlp files - plugin and java ok Melsync Linux - Software 1 06-25-2006 04:09 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 07:29 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration