Casting objects that do not have a relationship - java

Sorry if this question is too specific but I can't seem to think of the right terminology to explain it in an abstract way.
I have two classes for the same entity. One for saving it to the database
public class XDb extends SugarRecord {
private float ampX;
private float ampY;
}
and the other for Api calls:
public class XApi extends ApiFunctionality {
private float ampX;
private float ampY;
}
I first save the objects in the local database, then I read from the database and upload data to the server.
I want to be able to do something like this:
XApi xApi = (XApi) xDb;
Is there any functionality in java that supports this?
Apologies if I am still ambiguous.

In a word, no. You can't. They have to have some relationship. They could both implement a common interface, for example.

You cannot cast them, since the types are unrelated.
Assuming that you have:
Appropriate accessors (e.g. getAmpX() and getAmpY(), or non-private visibility of ampX and ampY - not recommended) on the class that you want to convert from (XDb in your example);
An appropriate constructor on the class that you want to convert to (XApi in your example)
then you can simply construct an instance of the latter using the properties of the former:
XApi xApi = new XApi(xDb.getAmpX(), xDb.getAmpY());

They must be of the same hierarchy tree,
if XApi inherits (extends) XDb, you will be able to cast.

Related

Java generics Factory Pattern with multiple Generics

I'm trying to learn how to use generics, but I am having a hard time with implementing a factory pattern. I want my DataFactory interface to have a method that returns an object of a class that extends Data. I believe the following code will work, but I'm having a hard time understanding something. Is there a way to avoid having to explicitly specify the second type in the DataFactory interface? Message extends Data<String>, so if T extends Data<U>, shouldn't the U be implied already?
Data class:
public abstract class Data<T> {
private final long id;
private final T content;
private final User sender;
...
}
Message class:
public class Message extends Data<String> {
...
}
DataFactory Interface:
public interface DataFactory<T extends Data<U>, U> {
T newInstance(U content, User sender);
}
MessageFactory Class:
public class MessageFactory implements DataFactory<Message, String> {
#Override
public Message newInstance(String content, User sender) {
return new Message(content, sender);
}
}
Why can't I just write:
public class MessageFactory implements DataFactory<Message>
I'm sorry if this is not a well worded question, I'm not exactly sure how to express it. Originally I didn't want to add type parameters to the class itself, just to the method, but I had more issues trying to make that work. I'm not even sure if I am implementing this correctly. Any help would be appreciated.
Because the type system itself doesn't know that, in the general case, you won't write GenericData<T> extends Data<T>. In this specific case, your Message class has a specific class for the generic type, but you could supply other parameters that wouldn't.
Even though the OP selected already an answer, I want to share additional, relevant information to help others that will come here looking for answers.
Why use generics?
First, we need to understand what is the reason to use generics in the first place. Generic type parameters provide a way for you to re-use the same code with different inputs. For example, you can use generic code to handle a collection of strings, or a collection of widgets with the same code. Before generics, the way we used to handle similar cases was by casting objects. For simplification, let us use OP example and make the Data class non-abstract.
public void doSomethingWithThisInput (Object o) {
if (o instanceof MyClass) {
MyClass myCls = (MyClass) o;
// do something here
}
}
If you ever dealt with Java Collection before generics, you are aware of how painful this used to be. Part of the problem of the old approach was that, in many cases, you didn't discover issues with casting during development. Almost 100% of these cases were discovered at runtime which everyone can agree is very bad. With generics, these issues of object incompatibility are discovered at compile time.
Use cases for generics
The main reason why you would want to use generics is to create a collection of similar "things" inside a class. Examples of this can be found all over the Java language with Set, List, Map, etc.
public abstract class Data<T> {
private T content;
// other methods and attributes omitted;
}
With such a class, you refer to the contents of the Data object generically. The data content can be literally anything: An Email object, a File object, or simply a String. Obviously, the intent here is that if you have a collection of data contents, each object should be of the same type. Creating a collection of disparate contents makes little sense and it is actually counterproductive.
PECS
This is probably the most important lesson you need to learn to how to use generics properly. **PECS** is an acronym that stands for Producers Extend Consumers Super. What does this mean? The best answer I can give you can be found here [https://stackoverflow.com/questions/2723397/what-is-pecs-producer-extends-consumer-super][1]. The link is to an answer here on SO about PECS.
Additional resource
Oracle Java Lesson: Generics

How to persist enum const in ormlite as a interface type?

I have one enum, which implements an interface. The purpose of this interface is only to create a bound between multiples enums, so that I can later implements a plugin system. (This post may clear the thing a little bit.)
My library enum lloks like this :
public interface Resource extends Displayable<Resource> {
// all the methods that implements my enum
// Displayable is just an interface that I need in my game
// Just doesn't consider it, it can't interfer
}
And an exemple of an enum that implements this interface :
public enum LibraryEnum implements Resource {
// static final fields
// fields and resources
// all implemented methods
}
The thing is that I want to store this as an interface, to enable a sort of enum inheritance, because I'm about to create a plugin system. Any dev would just have to implements this unique interface to add resources in the game. But I don't know how he (or she) would name it (there might be some doubles).
I have a class with the associated field, as shown here :
#DatabaseTable(tableName = "packs")
public class Pack implements Displayable<Pack> {
#DatabaseField(columnName = "id", generatedId = true)
private Long packId;
// Here it is
#DatabaseField
private Resource resource;
// Is there any annotation arguments to add ?
#DatabaseField
private int quantity;
// Some other fiels
// Then constructors and methods
}
I've read the docs a little bit, and it say to create a custom implementation of the DataPersister interface. So I began to do it, but there is so many methods to implement (20?), that I don't know where to began and where to end. Maybe it's the wrong way to do it?
The docs shows an exemple where are the methods aren't even there, and for the type that already exists in java (Date & DateTime).
How can I achieve this? Or is this even possible? If not, is there anyway to do what I want anyway (store unknown const enum fields in the database)?
I've read the docs a little bit, and it say to create a custom implementation of the DataPersister interface. So I began to do it, but there is so many methods to implement (20?), that I don't know where to began and where to end.
First off you should consider RTFM on custom persisters. I've spent a good bit of time on the ORMLite docs.
The right thing to do is to extend a currently implemented persister from ORMLite. For example, you could extend the BaseEnumType if you are persisting an enum. If none of the persisters work then you should extend the generic BaseDataType.
With BaseDataType, all you need to implement is:
public Object parseDefaultString(FieldType fieldType, String defaultStr);
public Object resultToSqlArg(FieldType fieldType, DatabaseResults results, int columnPos);
Although not required, you probably also want to override:
public Object sqlArgToJava(FieldType fieldType, Object sqlArg, int columnPos)
Typically you'd want to override a couple other methods to tweak the behavior of your custom persister.

Serializing a class containing a non-serializable class

I have two classes, A and B.
Class A is developed by X company and is not serializable.
Company Y is trying to use class A in class B, which must be serializable.
How can this be done without changing class A? Is that what the externalization interface is for?
Sure. You need to make fields in your class B referring to their class A transient (or use serialPersistentFields if I've spelt that correctly). Implement custom writeObject and readObject methods in B to save the required state of A in serialisable objects.
There is no need for Externalizable (pretty much ever).
As pointed out by #Tom Hawtin - tackline You have two ways to combat this situation:
1. Declare the instance variable of class A as transient..
private transient A a ;
Or,
2. By using serialPersistentFields. This instructs the JVM to persist only those fields which it has mentioned. Here is a short example:
public class B implements Serializable
{
private A a;
private String name ;
private int enrollment;
private static final ObjectStreamField[] serialPersistentFields =
{
new ObjectStreamField("name",String.class),
new ObjectStreamField("enrollment",int.class)
}; //This will cause only "name" and "enrollment" to persist while serialization
}
Yes, this can be done by implementing java.io.Externalizable - it allows you to implement serialization manually, by writing individual bytes (or more conveniently through methods like writeInt()). As long as you can get and set all information about an instance of class A from its public API, you can simply embed it into your custom serialized representation of classs B.

Is a superclass protected field which is only used in a subclass bad practice?

I have a superclass like this which I expect alot of classes to inherit:
public abstract class Super {
protected Object myField; //Not used anywhere in this class
//a load more code here which does useful stuff
}
All these classes will need to use an instance of myField. However the superclass does not. Have I made a bad design decision somewhere?
Not necessarily. If all the subclasses need the same field for the same reason, then that's no different than providing any other common functionality in a base class. as your classes grow you may find that you add common functionality which uses this field (e.g. referencing it in an equals/hashCode method).
Now, if the field is of type Object and each sub-class shoves something completely different into it, i would consider that a code smell.
Well IMHO, a field should not be present in a class if it's not really used by that class. What it seems to me that you really want here is to have a base class that tells its subclasses "you should ALL have some way of keeping state for X but I (the base class) will not modify that X state, in which case you should make an abstract method in order to convey that message, something like this:
public abstract class Super {
protected abstract Object getMyField();
}
It's hard to say with such a vague description, but it would seem like you could do some generalization and push some common code up into your superclass. If your subclasses are doing something similar with the field then some commonality could be found (using template methods or strategies to handle subclass-specific differences), otherwise if every subclass is doing something different with it then what's the point of using a common field?
No, I don't think so. Abstract class serve that purpose (Have common functionality in base class and let subclass implement only specific required functionality).
So, if you don't use that field in class Super - why do you need it there?
Perhaps your super class would provide an interface to interact with this field in generic way, for example:
public abstract class Super<T> {
protected T myField;
public T getField() {
return myField;
}
}
public class Child extends Super<String> {
public Child( String label ) {
super.myField = label;
}
}
As stated in this tuturial
A protected field or method is accessible to the class itself, its subclasses, and classes in the same package.
This means that the protected fields have been designed precisely to have these characteristics.
Just on a lighter note The only thing common in your hirarchy is one field then you should get rid of abstract class and Create one Marker Interface.

Java: extending Object class

I'm writing (well, completing) an "extension" of Java which will help role programming.
I translate my code to Java code with javacc. My compilers add to every declared class some code. Here's an example to be clearer:
MyClass extends String implements ObjectWithRoles { //implements... is added
/*Added by me */
public setRole(...){...}
public ...
/*Ends of stuff added*/
...//myClass stuff
}
It adds Implements.. and the necessary methods to EVERY SINGLE CLASS you declare. Quite rough, isnt'it?
It will be better if I write my methods in one class and all class extends that.. but.. if class already extends another class (just like the example)?
I don't want to create a sort of wrapper that manage roles because i don't want that the programmer has to know much more than Java, few new reserved words and their use.
My idea was to extends java.lang.Object.. but you can't. (right?)
Other ideas?
I'm new here, but I follow this site so thank you for reading and all the answers you give! (I apologize for english, I'm italian)
If it is only like a "research" project in which you want to explore how such extension would work, you could provide your own implementation of the Object class. Simply copy the existing object implementation, add your setRole method etc, and give -Xbootclasspath:.:/usr/lib/jvm/java-6-sun/jre/lib/rt.jar as parameter to the java command. (I will look for api-classes in . before looking in the real rt.jar.)
You should consider using composition rather than inheritence to solve this problem; that way you can provide the functionality you need without using up your "one-shot" at inheritence.
For example, the JDK provides a class PropertyChangeSupport, which can be used to manage PropertyChangeListeners and the firing of PropertyChangeEvents. In situations where you wish to write a class that fires PropertyChangeEvents you could embed a PropertyChangeSupport instance variable and delegate all method calls to that. This avoids the need for inheritence and means you can supplement an existing class hierarchy with new functionality.
public class MyClass extends MySuperClass {
private final PropertyChangeSupport support;
public MyClass() {
this.support = new PropertyChangeSupport(this);
}
public void addPropertyChangeListener(PropertyChangeListener l) {
support.addPropertyChangeListener(l);
}
protected void firePropertyChangeEvent() {
PropertyChangeEvent evt = new ...
support.firePropertyChangeEvent(evt);
}
}
you can extend Object - every class extends it.
you seem to need something like multiple inheritance - there isn't such a thing in Java
if you want to add functionality, use object composition. I.e.,
YourClass extends Whatever implements ObjectWithRoles {
private RoleHandler roleHandler;
public RoleHandler getRoleHandler() {..} // defined by the interface
}
And then all of the methods are placed in the RoleHandler
If you're talking about adding a role to all your objects I would also consider an annotation-based solution. You'd annotate your classes with something like #Role("User"). In another class you can extract that role value and use it.
I think it would need an annotation with runtime retention and you can check, run-time, whether the annotation is present using reflection and get that annotation using getAnnotation. I feel that this would be a lot cleaner than extending all your classes automatically.
I believe there are some frameworks which use exactly such a solution, so there should be example code somewhere.
If you are doing what you are doing, then inheritance is probably not the correct idiom. You may want to consider the decorator pattern, whereby you construct a class that takes as its parameter some other class with less functionality, and adds some additional functionality to it, delegating to the existing class for functionality that already exists. If the implementation is common to many of your decorators, you may want to consider putting that functionality in class that can be shared and to which you can delegate for all your decorators. Depending on what you need, double-dispatch or reflection may be appropriate in order to make similar but not quite the same decorators for a large variety of classes.
Also, as has been pointed out in the comments, String is declared "final" and, therefore, cannot be extended. So, you should really consider a solution whereby you delegate/decorate objects. For example, you might have some object that wraps a string and provides access to the string via getString() or toString(), but then adds the additional functionality on top of the String class.
If you just want to associate some objects with additional attributes, use a Map (e.g. HashMap).
What you really want to do would be monkey patching, i.e. changing the behaviour of existing classes without modifying their code.
Unfortunately, Java does not support this, nor things like mixins that might be used alternatively. So unless you're willing to switch to a more dynamic language like Groovy, you'll have to live with less elegant solutions like composition.

Categories