I have a class named as order in package com.abc
I have another class named as order in different package in different project named as com.bcd
Both order classes have same code get, set functions and variables with no changes.
Then I have objects
com.abc.order obj1 = new com.abc.order();
com.bcd.order obj2 = new com.bdc.order();
Now I have to pass arguments to a function and it takes only obj2 as parameters
How can I convert type of obj1 into type of obj2
I cannot change parameters for the function.
Looking forward to your reply.
thanks.
Have a look at Apache Commons BeanUtils to copy properties from one object to another.
http://commons.apache.org/beanutils/v1.8.3/apidocs/index.html
Something like
BeanUtils.copyProperties(obj2, obj1)
should do the trick.
You have to copy each field. You can use a BeanIntrospector to help you do this.
You could overload the function, simply by typing it again in your code, but this time so it will take instances of com.abc.order instead. Keep the other one too of course.
If you have defined these two functions, it will work. Problem is duplication. I've never seen a situation like this before and it doesn't sound like good coding practice to duplicate a class and use both in the same code. Can you cast them into each other? like (obj1) obj2? I don't think you can but I'm not 100% sure...
The best solution, if you can is to eliminate one of the two classes especially if they are identical.
Otherwise rename them (first letter capitalised, if possible), again if you can.
Finally, if you cannot perform either of the above, write a conversion method on one or both classes, resolve between the classes where used by retaining their package in all usages.
import com.abc.order;
abc.order obj1 = new abc.order();
bcd.order obj2 = new bdc.order();
you can make the class com.bdc.order subclass of com.abc.order
can you clarify why u want to do this ?
Related
I have a set of classes in my program which can be instantiated. Each class has a static method associated with it which updates a particular aspect of that class.
At run time the program chooses to use a number of the classes from the set.
Multiple versions of these classes are then instantiated as objects as the program runs.
Throughout the program there are key points where I need to call the static methods associated with the various classes but only the ones in use that the program picked at run time.
Is it possible for me to make a list/array containing the classes in use without instantiating them? So that I can then just go through that list and call the static method on each class?
The only other way I have found of doing it is instantiating one object for each class in use and storing them in an array and calling the methods from there. This seems a bit inefficient and not very elegant.
Any help is greatly appreciated.
You could use reflection to do something like this:
List <Class<?>> classes = new ArrayList<Class<?>>();
// alternatively, classes.add(com.foo.MyClass1.class);
classes.add(Class.forName("com.foo.MyClass1"));
classes.add(Class.forName("com.foo.MyClass2"));
// ...etc
Method m = classes.get(0).getDeclaredMethod("staticFunction");
m.invoke(null); // pass in an instance of the class if this is an instance method
Check out the javadoc for Class and Method.
I'm not sure why you want to avoid instantiation, but if the only thing you are doing is calling static methods, there is not reason to create objects. As for your question, you can create an Array of Classes without any problem. Remember that MyClass.class is actually an object of class Class, so this would work :
Class[] classes = new Class[] {MyClass1.class, MyClass2.class};
You can then use your logic to select some of them. When done, you can instantiate them using reflection :
classes[0].newInstance();
Hope it helps, if not, please precise your question. Note that the class objects themselves will be created (not sure you can prevent the class loader to load them).
You can have a list of Class objects such as
List<Class> myClasses = new ArrayList<Class>();
To add an item to the list you code something like myClasses.add(Class1.class);
That's one way to store a list of classes, without needing to create an instance of each one.
Suppose I have an Employee class. How can I implement an ArrayList only containing Employee elements without using generics? That is, without Arraylist<Employee>, how can I restrict the ArrayList to add only Employee objects?
Extend ArrayList and customize add() and addAll() method to check the object being added is instanceof Employee
You could use a wrapper class that holds a private ArrayList field, say called employeeList, has a
public void add(Employee employee) {
employeeList.add(employee);
}
as well as any other necessary methods that would allow outside classes to interact with the ArrayList in a controlled fashion.
I find it much better to use composition for this than inheritance. That way if you wanted to change from an ArrayList to something else, say a LinkedList, or even something completely different, you would have an easier time.
You could use Collections.checkedList() - but why would you want to not use generics?
Subclass the ArrayList class and name it something like EmployeeArrayList.
If you're wanting to avoid generics for their own sake, e.g. for compatibility with very old versions of Java, then extending or wrapping ArrayList won't help - you probably want to find or make another array implementation that has the same functionality.
Basically, ArrayList is just a wrapper for a primitive array that copies and pastes its data into a larger array when necessary, so this isn't especially difficult to write from scratch.
What exactly do you want when you "restrict"? There are two possible places where one could place a restriction: at compile-time or runtime.
Generics is a purely compile-time thing. It helps you write correct code but you can still bypass it and put the wrong type in the array and it won't complain at runtime.
On the other hand, something like Collections.checkedList()is a runtime restrictions. It throws an error at runtime when an object of the wrong type comes. But it does not help you at compile-time if you do not have generics.
So the two things are orthogonal, and neither is a replacement for the other. What exactly do you want?
I know this is simple but I don't really understand the question...
Assume the signature of the method xMethod is as follows.
Explain two different ways to invoke xMethod:
public static void xMethod(double[] a)
I thought to invoke a method you just do:
xMethod(myarray);
What could it mean by asking two different ways? Maybe I'm just looking into the question too much.
For kicks, show your professor this:
XClass.class.getMethod("xMethod", a.getClass()).invoke(null, a);
Then tell them the two answers are
XClass.xMethod(a);
//and
xObject.xMethod(a); //this is bad practice
If this is for a first time java class, my guess is he is looking for these 2 cases:
//the one you have, using a precreated array
double[] myArray = {1.1, 2.2, 3.3}
xMethod(myarray);
//and putting it all together
xMethod(new double[]{1.1, 2.2, 3.3});
Basically illustrating you can make an array to pass, or simply create one in the call.
Just a guess though
You could invoke it either by calling it on a class, or via an instance of that class.
Foo.xMethod(a);
or:
Foo foo = new Foo();
foo.xMethod(a);
The first approach is prefered, but the second one will compile and run. But be aware that it is often considered a design flaw in the language that the second approach is allowed.
static methods are not bound to the construction of the class.
The method above can be called either by constructing the class or just by using the namespace:
Classname myclass = new Classname();
myclass.xMethod(myarray);
or you could just do:
Classname.xMethod(myarray);
as you see, you don't have to construct the class in order to use the method. On the other hands, the static method can't access non-static members of the class.
I guess that's what the question meant by 2 different ways...
There is only one valid way to do this:
YourClass.xMethod(myDoubleArray);
But, you can write non-totally-correct Java:
YourClass instance = new YourClass();
instance.xMethod(myDoubleArray);
This will work, but is considered as wrong. The Java compiler will even complain about it. Because a there is no need of invoking a static method by creating an instance of the class. Static means that the method is instance independent. Invoking it through an instance is pointless and confusing.
Later on, you will see that there is a second correct way of doing it, ie "reflection". But that is an advanced topic, so I assume you are not supposed to know this already.
I have two classes in my Java project that are not 'related' to each other (one inherits from Thread, and one is a custom object. However, they both need to use the same function, which takes two String arguments and does soem file writing stuff. Where do I best put this function? Code duplication is ugly, but I also wouldn't want to create a whole new class just for this one function.
I have the feeling I am missing a very obvious way to do this here, but I can't think of an easy way.
[a function], which takes two String arguments and does soem file writing stuff
As others have suggested, you can place that function in a separate class, which both your existing classes could then access. Others have suggested calling the class Utility or something similar. I recommend not naming the class in that manner. My objections are twofold.
One would expect that all the code in your program was useful. That is, it had utility, so such a name conveys no information about the class.
It might be argued that Utility is a suitable name because the class is utilized by others. But in that case the name describes how the class is used, not what it does. Classes should be named by what they do, rather than how they are used, because how they are used can change without what they do changing. Consider that Java has a string class, which can be used to hold a name, a description or a text fragment. The class does things with a "string of characters"; it might or might not be used for a name, so string was a good name for it, but name was not.
So I'd suggest a different name for that class. Something that describes the kind of manipulation it does to the file, or describes the format of the file.
Create a Utility class and put all common utility methods in it.
Sounds like an ideal candidate for a FileUtils class that only has static functions. Take a look at SwingUtilities to see what I'm talking about.
You could make the function static in just one of the classes and then reference the static method in the other, assuming there aren't variables being used that require the object to have been instantiated already.
Alternatively, create another class to store all your static methods like that.
To answer the first part of your question - To the best of my knowledge it is impossible to have a function standalone in java; ergo - the function must go into a class.
The second part is more fun - A utility class is a good idea. A better idea may be to expand on what KitsuneYMG wrote; Let your class take responsibility for it's own reading/writing. Then delegate the read/write operation to the utility class. This allows your read/write to be manipulated independently of the rest of the file operations.
Just my 2c (+:
In my answer from yesterday I called the following piece of code "a hack":
final class MyMap extends HashMap<SomeSuperLongIdentifier, OtherSuperLongIdentifier> {}
// declared MyMap as an alias for readability purposes only
MyMap a = new MyMap();
a.put("key", "val");
Giving it another thought, this does not seem like a bad idea at all, but I might be missing something. Are there any potholes I missed out on? Is this an acceptable (possibly creative) way for declaring aliases in Java?
The drawback would be that you won't be able to directly use any methods that return a correctly typed Map, because they will never return a MyMap. Even if they could return a Map<SomeSuperLongIdentifier, OtherSuperLongIdentifier>.
For example you wouldn't be able to use the filter() methods in Maps (provided by Google Collections). They would accept a MyMap instance as input, but they would return only a Map<SomeSuperLongIdentifier, OtherSuperLongIdentifier>.
This problem can be somewhat reduced, by writing your MyMap to delegate to another Map implementation. Then you could pass the return value of such a method into the constructor and still have a MyMap (without copying, even). The default constructor could just set the delegate to a new HashMap instance, so the default usage would stay the same.
I would object to the name MyMap: Since you create an alias, make it document its purpose by giving it a useful name. Other than that, I like it.
I think it surely a convenient way to declare type synonyms. Some languages have direct support for that (in Delphi (pascal), for example, you can do that like that:
type MyMap = HashMap<SomeSuperLongIdentifier, OtherSuperLongIdentifier>;
Since Java does not, I think you can use inheritance for that. You need to document, that this declaration is just a synonym and noone should add meethods to this class. Note also, that this consumes a little memory for VMT storage.
I personally would not do this, and would flag it in a review, but this is a matter of opinion.
Google Collections helps mitigate this problem, by letting you declare:
Map<SomeSuperLongIdentifier, OtherSuperLongIdentifier> a = Maps.newHashMap();
I'd look for ways to refactor code to not have to declare so many instances of this Map, perhaps.
As long as developers using your code have IDEs and are able to quickly jump to the class definition and read the comments for its purpose (which are in place, no?), I can see nothing wrong with it.
I wouldn't call it an 'alias'. It isn't. It can't be used interchangeably with the type it is supposed to be aliasing. So if that's the intention, it fails.
I think that inheritance is a very big gun compared to the problem at hand. At the very least I would have made this "alias class" final, with a big fat comment describing the reason for its existence.
Well, there are two contradictory aspects here.
On a modelling point of view, your declaration is right, because it emphasizes the encapsulation your class provides.
On a coding point of view, your declaration may be considered as wrong because you add a class only as a modelling support, with absolutely no added feature.
However, I find your approach quite right (although I never though about it before), since it provides a much appreciated (well, to me, at least) compilable model : classes from your model are perfectly reflected in your code, making your specifications executable, what is very cool.
All this brings me to say it's definitely a great idea, provided you support it with documentation.
I wouldn't call it a hack. Personally, I've created an alias for the purpose of declaring generic type parameters which cannot be changed and creating some clarity.
You also couldn't use this map in serialization if sending to another jvm which does not have your MyMap class.