ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
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?
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.
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.
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.
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());
}
}
}
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.
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.
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?.
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
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
}
}
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.