At somewhere, that I can not remember, I read about an alternative way to instatiate a object:
Generally, we instantiate (and assign) this way:
User userObj = new User();
userObj.setId(1);
userObj.setName("Foo");
An alternative way could be:
User userObj = new User()
{{
setId(1);
setName("Foo");
}}
I was using this alternative, and it works.
1) Anyone knows what is it? Where is Java documentation link that metion about it?
I stop to use this because I was having problems with interfaces that ClassName implements, but the alternative way don't implements. Oo
public class User implements Serializable
{
private int id;
private String name;
//public Getters and Setters
}
2) When I try to serialize and use it (passing from one activity to another, using:
putExtra(String, Serializable)
it will throw NotSerializableException. Why?
Edit 1: An anonnymous class also implements the parent 'implementations', like Serializable from ClassName?
You are using anonymous class with initialization block. So it's just an equivalent to the:
SubClass extends ClassName{
{
classObj.setParam1(1);
classObj.setParam2(1);
}
}
new SubClass();
There is nothing wrong with this construction - but please notice that you are not creating object of ClassName class, but object of SubClass class.
As I said you are using anonymous class (class without name). This is bad - cause while serialization / deserialization JVM should exactly know what is the class of serialization data, so basically - don't use anonymous classes if you want to serialize them.
Ad 1.: This construct ist called "anonymous class".
Ad 2.: I bet your class contains a field which is not Serializable.
Related
ok - I am walking a resource tree looking for classes that extend a particular super class, possibly not directly - I have code that works, but I'm having to resolve a concrete class, and I'm just wondering whether the same thing is possible without actually resolving the class - here is my working function:
private static <T> boolean checkInherits(Class<T> superClass, ClassMetadata classInformation)
{
try
{
Class<?> theClass = Class.forName(classInformation.getClassName());
return superClass.isAssignableFrom( theClass );
}
catch (Throwable theException)
{
return false;
}
}
So - is it possible to do that without using class.forName()? ie straight from the class metadata?
There is no way. A (non-final) class Foo cannot "know" about all of its (direct or indirect) subclasses because anyone can create a class that extends Foo. Hence, you can only learn about subclass relationships once you have both Class objects.
Assuming ClassMetadata is from the Spring framework (javadoc), you could use .getSuperClassName() to get the String representation of the superclass, but this won't solve your problem if the subclass relationship isn't direct. The only way to get the Class object from a ClassMetadata is by using Class.forName(classInformation.getClassName()), exactly as you've already done.
I was wondering, if I can cheat serialization by wrapping them in local nested classes, something like this:
I have a service which I need to pass around, but it internally has some very complex data.
interface ComplexService {
IncredibleComplexObject getData();
}
So I thinking about wrapping it in another class that is serializeable via decorator pattern.
public final class Utils {
public static Serializable wrap(final ComplexService service) {
class WrapperService implements ComplexService, Serializeable {
#Override
public IncredibleComplexData getData() {
return service.getData();
}
};
return new WrapperService();
}
}
I actually don't believe that I can cheat serialization like that, because it would be a little bit too much magic if Java could actually recreate my class that is dependent on my final ComplexService-parameter. But I am wondering, why exactly this fails and what exception would be thrown, where and why.
(just for clarification why I would want to do this: I am on android and I need to pass this service to a Fragment, which naturally can only save serializeable objects).
Yes, you can wrap your non-serializable object in a serializable wrapper. No, it won't magically make the wrapped object serializable. You'll get a NotSerializableException if you attempt to serialize the wrapper class (without making that field transient).
I guess this is a bad pattern, whats the best approach to fix it?
I mean I would like everybody using a constructor with 2 arguments,but I need to leave default constructor because its implementing a listener which classloads it without args. I would like to hide default constructor to anyone else but the listener handler which uses it, and make the other the unique point to instantiate.
Is there any kind of annotation? any privacy modifier for certain classes (system caller one is not in the same package)?
This seems fine to me. You would do the same thing if you want to instantiate a class differently during unit testing.
Oh, I see you need a constructor that has more access than protected but less than public. Unfortunately that's not possible.
You could put both your class MyClass and the listener MyListener that needs to use the empty constructor in the same package. Then, set the access of the empty constructor to package-level:
package com.stackoverflow.foo;
public class MyClass {
MyClass () { // package-private (no explicit access modifier)
}
public MyClass(int a, int b) { // public
}
}
package com.stackoverflow.foo;
public class MyListener {
private MyClass ref = new MyClass(); // MyListener is on the same package as MyClass, so this is valid
}
This way, you ensure that only classes that are on the same package as MyClass can use the default constructor.
I'm having trouble to find how to typecast the dynamically created class while using reflection.
String s;
...
Class unknownClass = Class.forName(s);
Constructor defaultConstructor = unknownClass.getConstructor(null);
Object retobj = defaultConstructor.newInstance(null);
retobj.Writeout(); // This won't work since;
The object class does not have a method called Writeout, but that is the name of the method which is shared by nine other possible classes that is dynamically created here (needless to say every Writeout method does a seperate thing). Any suggestions ? Thx in advance for your time.
Use reflection Luke...
Method writeOutMethod = unknownClass.getMethod("Writeout", new Class[]{});
writeOutMethod.invoke(retobj, new Object[]{});
Or, ensure that your objects implement a well known interface (the clean approach).
The 9 classes should all implement a single interface (let's call it Output) which declares the writeOut() method. The code would thus be:
Output retobj = (Output) defaultConstructor.newInstance(null);
retobj.writeOut();
Note that you could just use unknownClass.newInstance() to invoke the no-arg constructor.
Side note: please respect tha Java naming conventions: methods start with a lower-case letter.
Cast it:
((YourObjectWithThatMethod) retobj).Writeout();
EDIT (see the comment from Kevin Welker):
If all of your 9 classes implement the same interface, you can cast every class to that interface:
((YourInterface) retobj).Writeout();
If all nine classes share a super-class or an interface which declares/implements writeOut then you can cast retobj to that interface and then call it.
public interface Writable {
public void writeOut();
}
Then each class needs to have in the class declaration.
class MyClass implements Writable {
}
Then you can say
((Writable) retobj).writeOut();
I have some Serializable Objects which I use with GWT's RPC mechanism.
I decided to make them all sub-class an Object containing common fields such as "id", "revision" etc.
However, I've noticed that GWT does not serialize fields of the super-class, so I just get every super-class field as null on the client-side.
How can I get the super-class fields serialized as well without having to write a CustomFieldSerializer for each and every one of my Serializable classes? Is it possible?
Example:
public class Super {
private String id;
public String getId() {
return id;
}
}
public class Sub extends Super implements Serializable {
private String name;
// more stuff here
}
// on the client side, inside an AsyncCallback
onSuccess(Sub sub) {
assert(sub.getId() != null);
}
So, when I send this through GWT's RPC mechanism to the client-side, I get a null value in the 'id' field of any instance of Sub. I ensured that in the server, id is not null. I also tried to make the super-class implement Serializable, without luck.
Any advices welcome.
For serialize any class in gwt you have to implements Serializable in super class.
To pass a bean you have to fulfill the following requirements (from GWT site):
1.It implements either Java Serializable or GWT IsSerializable interface, either directly, or because it derives from a superclass that does.
2.Its non-final, non-transient instance fields are themselves serializable
3.It has a default (zero argument) constructor with any access modifier (e.g. private Foo(){} will work)
The problem may have different causes.
1.Verify that the class has a default constructor (without arguments)
2.Verify that the class implements Serializable or IsSerializable or implements an Interface that extends Serializable or extends a class that implement Serializable
3.Verify that the class is in a client.* package or …
4.Verify, if the class is not in client.* package, that is compiled in your GWT xml module definition. By default is present. If your class is in another package you have to add it to source. For example if your class is under domain.* you should add it to xml as . Be aware that the class cannot belong to server package!
5.If you are including the class from another GWT project you have to add the inherits to your xml module definition. For example if your class Foo is in the package com.dummy.domain you have to add to the module definition.
6.If you are including the class from another GWT project released as a jar verify that the jar contains also the source code because GWT recompile also the Java source for the classes passed to the Client.
If you want the data in Super to be serialized, you must make it Serializable.