Define constraints on the context in which as class is instantiated - java

I wonder if there's a way to define a class in such a way that instances of it will never be members of another class (only local variables), or the other way round - only members but never local.
Is there any way in which a class can dictate the scope of it's prospective instances?

I don't think so. But I have no definitive proof.

To limit the scope you'd some sort of class annotation or class modifier and the virtual machine needed the functionality to check, whether a class (or any subclass of this restricted class) was assigned to a member or local variable and violated the constraint.
Just imagine, you had a class with the - just invented - 'onlylocal' modifier, indicating that you only allow instances in local variables.
public onlylocal class LocalUseOnlyClass implements Serializable {
//...
}
and in another class someone just did in a constructor:
private Object member;
public MyOtherClass(Serializable something) {
this.member = something
}
The Compiler couldn't detect, if you passed an instance of LocalUseOnlyClass to that constructor, so the JVM had to check and throw an exception or an error.
BTW & OT: what's your intention? - maybe there's an alternative to fulfill your underlying requirement.

no. member and local variable can be assigned to each other.

Related

Why you cannot declare member interfaces in a local class?

You cannot declare an interface inside a block like below
public void greetInEnglish() {
interface HelloThere {
public void greet();
}
class EnglishHelloThere implements HelloThere {
public void greet() {
System.out.println("Hello " + name);
}
}
HelloThere myGreeting = new EnglishHelloThere();
myGreeting.greet();
}
In This Oracle tutorial I got "You cannot declare member interfaces in a local class." because "interfaces are inherently static."
I am eagar to understand this with more rational information, why and how interface are inherently static?
and why above code does not make sense?
Thanks in advance to elloborate!
I am eagar to understand this with more rational information, why and
how interface are inherently static?
because interfaces are implicitly static, and you can't have non-final statics in an inner class.
Why are they implicitly static?
because that's the way they designed it.
and why above code does not make sense?
because of the above reason ,
Now lets make it simple :
What static means - "not related to a particular instance". So, suppose, a static field of class Foo is a field that does not belong to any Foo instance, but rather belongs to the Foo class itself.
Now think about what an interface is - it's a contract, a list of methods that classes which implement it promise to provide. Another way of thinking about this is that an interface is a set of methods that is "not related to a particular class" - any class can implement it, as long as it provides those methods.
So, if an interface is not related to any particular class, clearly one could not be related to an instance of a class - right?
I also suggest you to study Why static can't be local in Java?
Any implementations can change value of fields if they are not defined as final. Then they would become a part of the implementation.An interface is a pure specification without any implementation.
If they are static, then they belong to the interface, and not the object, nor the run-time type of the object.
An interface provide a way for the client to interact with the object. If variables were not public, the clients would not have access to them.
Your code does not make sense because you define the interface within the body of a method. You can define an interface either at top level or in another class or interface.
You cannot declare an interface inside a block
reference

Is it possible to serialize anonymous class without outer class?

I made a small research on web and reviewed related topics on this site, but the answers were contradictory: some people said it is not possible, others said it is possible, but dangerous.
The goal is to pass an object of the anonymous class as a parameter of the RMI method. Due to RMI requirements, this class must be serializable. Here's no problem, it is easy to make class Serializable.
But we know that instances of inner classes hold a reference to an outer class (and anonymous classes are inner classes). Because of this, when we serialize instance of inner class, instance of outer class is serialized as well as a field. Here's the place where problems come: outer class is not serializable, and what's more important - I do not want to serialize it. What I want to do is just to send instance of the anonymous class.
Easy example - this is an RMI service with a method that accepts Runnable:
public interface RPCService {
Object call(SerializableRunnable runnable);
}
And here is how I'd like to call the method
void call() {
myRpcService.call(new SerializableRunnable() {
#Override
public Object run {
System.out.println("It worked!");
}
}
}
As you can see, what I want to do is to send an "action" to the other side - system A describes the code, that should be run on system B. It is like sending a script in Java.
I can easily see some dangerous consequences, if this was possible: for example if we access a field or captured final variable of outer class from Runnable - we'll get into a trouble, because caller instance is not present. On the other hand, if I use safe code in my Runnable (compiler can check it), then I don't see reasons to forbid this action.
So if someone knows, how writeObject() and readObject() methods should be properly overriden in anonymous class OR how to make reference to outer class transient OR explain why it is impossible in java, it will be very helpful.
UPD
Yet another important thing to consider: outer class is not present in the environment that will execute the method (system B), that's why information about it should be fully excluded to avoid NoClassDefFoundError.
You could try making Caller.call() a static method.
However, the anonymous class would still need to be available in the context in which you deserialize the serialized instance. That is unavoidable.
(It is hard to imagine a situation where the anonymous class would be available but the enclosing class isn't.)
So, if someone can show, how I can properly override writeObject and readObject methods in my anonymous class ...
If you make Caller.call() static, then you would do this just like you would if it was a named class, I think. (I'm sure you can find examples of that for yourself.)
Indeed, (modulo the anonymous class availability issue) it works. Here, the static main method substitutes for a static Classer.call() method. The program compiles and runs, showing that an anonymous class declared in a static method can be serialized and deserialized.
import java.io.*;
public class Bar {
private interface Foo extends Runnable, Serializable {}
public static void main (String[] args)
throws InterruptedException, IOException, ClassNotFoundException {
Runnable foo = new Foo() {
#Override
public void run() {
System.out.println("Lala");
}
};
Thread t = new Thread(foo);
t.start();
t.join();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(foo);
oos.close();
Foo foofoo = (Foo) new ObjectInputStream(
new ByteArrayInputStream(baos.toByteArray())).readObject();
t = new Thread(foofoo);
t.start();
t.join();
}
}
Another important thing to remember about: the Caller class is not present in the environment, that executes the method, so I'd like to exclude all information about it during serialization to avoid NoClassDefFoundError.
There is no way to avoid that. The reason that deserialization in the remote JVM is complaining is that the class descriptor includes a reference to the outer class. The deserializing side needs to resolve that reference even if you managed to clobber the reference, and even if you never explicitly or implicitly used the synthetic variable in the deserialized object.
The problem is that the remote JVM's classloader needs to know the type of the outer class when it loads the classfile for the inner class. It is needed for verification. It is needed for reflection. It is needed by the garbage collector.
There is no workaround.
(I'm not sure if this also applies to a static inner class ... but I suspect that it does.)
Attempting to serialize anonymous Runnable instance without outer class refers not only to a serialization problem, but to a possibility of arbitrary code execution in another environment. It would be nice to see a JLS reference, describing this question.
There is no JLS reference for this. Serialization and classloaders are not specified in the JLS. (Class initialization is ... but that is a different issue.)
It is possible to run arbitrary code on a remote system via RMI. However you need to implement RMI dynamic class loading to achieve this. Here is a reference:
http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/guide/rmi/spec/rmi-arch.doc.html#280
Note that adding dynamic class loading for remote classes to RMI introduces significant security issues. And you have to consider issues like classloader leaks.
If you mad enough to do the trick you can use reflection to find field that contains reference to outer class and set it to null.
Your example as stated above cannot work in Java because the anonymous inner class is declared within class Caller, and you explicitly stated that class Caller in not available on the RPC server (if I understood that correctly). Note that with Java RPC, only data is sent over the network, the classes must already be available on the client and the server. It that respect your example doesn't make sense because it looks like you want to send code instead of data. Typically you would have your serializable classes in a JAR that is available to the server and the client, and each serializable class should have a unique serialVersionUID.
You can't do exactly what you want, which is to serialize an anonymous inner class, without also making its enclosing instance serializable and serializing it too. The same applies to local classes. These unavoidably have hidden fields referencing their enclosing instances, so serializing an instance will also attempt to serialize their enclosing instances.
There are a couple different approaches you can try.
If you're using Java 8, you can use a lambda expression instead of an anonymous inner class. A serializable lambda expression does not (necessarily) have a reference to its enclosing instance. You just need to make sure that your lambda expression doesn't reference this explicitly or implicitly, such as by using fields or instance methods of the enclosing class. The code for this would look like this:
public class Caller {
void call() {
getRpcService().call(() -> {
System.out.println("It worked!");
return null;
});
}
(The return null is there because RPCService.Runnable.run() is declared to return Object.)
Also note that any values captured by this lambda (e.g., local variables, or static fields of the enclosing class) must also be serializable.
If you're not using Java 8, your next best alternative is to use a static, nested class.
public class Caller {
static class StaticNested implements RPCService.Runnable {
#Override
public Object run() {
System.out.println("StaticNested worked!");
return null;
}
}
void call() {
getRpcService().call(new StaticNested());
}
}
The main difference here is that this lacks the ability to capture instance fields of Caller or local variables from the call() method. If necessary, these could be passed as constructor arguments. Of course, everything passed this way must be serializable.
A variation on this, if you really want to use an anonymous class, is to instantiate it in a static context. (See JLS 15.9.2.) In this case the anonymous class won't have an enclosing instance. The code would look like this:
public class Caller {
static RPCService.Runnable staticAnonymous = new RPCService.Runnable() {
#Override
public Object run() {
System.out.println("staticAnonymous worked!");
return null;
}
};
void call() {
getRpcService().call(staticAnonymous);
}
}
This hardly buys you anything vs. a static nested class, though. You still have to name the field it's stored in, and you still can't capture anything, and you can't even pass values to the constructor. But it does satisfy your the letter of your initial question, which is how to serialize an instance of an anonymous class without serializing an enclosing instance.
The answer is no. You cannot do that since Inner class will need outer class to be serialized. Also you would run into troubles when you'd try to call the instance method of the outer class within the inner class. Why don't you just have another top level class which you could send?
I'd like to add to this topic. There is a way to achieve what you want, but will require reflection.
Here is a good tutorial on implementing a custom serializable object using writeObject and readObject
And here is a good tutorial (website font is kind of an eyesore, but the content is worth it) on on how Reflection is used to for serialization. The tutorial refers to final fields, but applies to any field.
You'll have to use Reflections getDeclaredField

General programming question about scope

This is more of a general programming question so the code examples I give will just be pseudo-code. I program in C++, Java, and Python so the pseudo-code is a mix of those. I am not too sure what the name of this is called so if you could give me a name for this, I can Google for more information about it I would greatly appreciate it.
Let's say I have a class called A. In this class, I create an instance of a class called B:
class A {
//instance variables
classB;
variable1;
variable2;
//instance methods
instanceFunction(parameter1, parameter2) {
//Do Stuff
}
function1(parameter1) {
classB = new B(some parameters);
}
setVariable1(value) {
variable1 = value;
}
getVariable2() {
return variable2;
}
}
In class B, I want to make changes to or make use of instance variables in class A. I can do this by passing a reference to A into B. So my A::function1 would look like this:
function1(parameter1) {
variable1 = new B(this, other parameters);
//Python syntax:
//variable1 = B(self, other parameters)
}
and my class B would look like this:
class B {
//instance variables
parentClass;
variable2;
//instance methods
instanceFunction(classA, other parameters) {
parentClass = classA;
}
function1() {
parentClass.setVariable1(someValue);
}
function2() {
variable2 = parentClass.getVariable2();
}
}
What other ways are there to have use of the variables in class A inside of class B?
If the code was C++ or Java, assume all variables are private and all methods and functions are public. Also assume all variables are passed by references or a pointers.
Edit:
First, thanks for all the responses!
Some clarification:
The reason I am asking this question is I have done a good amount of Qt programming in C++ and Python. In Qt, there are signals and slots. This lets inner objects tell the outer object to do something. For example I have an object A with objects B and C inside of it. Some change happens to object B and B needs to let A and C know. So B will emit a signal. A will catch this signal and do what it needs to do. Then, A will also let C know that B emitted this signal. This way C can do what it needs to do.
The reason I asked my question is because I was wondering how I can do something like I described without using the Qt libraries.
Also, let's assume B "is not" an A so I can't/don't want to use inheritance.
I am not too sure what the name of this is called...
I am having trouble following your pseudo-code, but you might be able to accomplish what you're looking for via:
Inheritance, which allows derived classes to access protected variables from a base class (static or instance variables)
Friend functions (C++) (which allows functions to have access to private instance variables on a class)
Dependency Injection (But probably only if you have more complex requirements than you're actually stating in your question. In this super-simple case, you'd just be accessing public properties or fields when an instance is passed in to a function - you might have to access them through a public getter/setter, since you want the variables to be private)
Edit:
After your edits, it is pretty clear that you want the Observer Design Pattern. This allows you to decouple the code that responds to a state change from the code that signals the state change.
That pattern is less about access to variables (as my first links were about), than it is about responding to events (or "state transitions", if you think about your class as a Finite State Machine).
Given the edit you made; It may be practical to implement a sig/slot mechanism using boost::signals, or the threadsafe signals2 (also in boost). This is implying that you are looking for a behaviour similar to Qt's sigslot mechanism. There are also many alternatives, look at the SO question here.
Explicitly passing this (or perhaps a proxy around this) is pretty much the only (sane, anyway) way to do it, assuming they need to be seperate objects. An object can't and shouldn't need to know number and location of its references. And even if you could get a list of all references to itself, that list could easily contain local variables, items in collections, potentially several instances of A, etc. - how is it supposed to know which one to chose as its parent?
If a B actually "is an" A, you should just make it a subclass.
What other ways are there to have use of the variables in class A
inside of class B?
Since your variables are not static, they are instance variables, so variable1 and variable2 are only meaningful in the context of a specific instance of A - so there needs to be a reference to that instance, not matter how you shape it.
For example, inner classes in Java can use variables of the enclosing outer class directly, but in reality this is just an illusion maintained by the compiler, and in the bytecode, the inner class actually keeps a reference to the outer class instance.
In C++, there is a concept of friend classes: a class A can declare another class B to be its friend, something which gives B access to the private variables of A. Simply write friend class B; inside of A. (As #delnan reminds us, you still need to manually give B a reference to A.)
In Java, if you declare B inside of A, B will become an inner class. Inner classes can only be instantiated from an instance of the outer class, and the instance of the inner class will be tied to the corresponding instance of the outer class, and may access its private variables.
(I agree with #mellamokb, though: This is probably a bad idea, as it creates very tight coupling between the two classes. You might want to rethink your class structure. What exactly are you trying to use this for?)
To reduce coupling between the objects, you shouldn't let B have a reference to A - you should give it a reference to an interface implemented by A. The difference is subtle, but it really makes you think about what actions or data really need to be shared across the interface boundary.

Initialization of Java - Class v/s Interface

I am stuck at the below concept of initialization of java class and interface :
I read the following sentence in the below mentioned book :
An interface is initialized only because a non-constant field declared by the interface is used, never because a subinterface or class that implements the interface needs to be initialized.
But that isn't the case when we initialise any java class.
Thus, initialization of a class requires prior initialization of all its superclasses, but not its superinterfaces.
Initialization of an interface does not require initialization of its superinterfaces.
My question is Why is this so ?
Any help would be greatly appreciated !
Thanks
PS : Book - "Inside the Java Virtual Machine" by Bill Venners (Chapter 7 - LifeTime of a class )
The only things you can declare in an interface are method signatures and constant fields. The latter can be initialized using constant values (i.e. string literals, integers, etc., possibly in some combination) or using non-constant values (i.e. method calls). Thus if an interface doesn't have any non-constant fields, no initialization is required -- everything is known at compile time. If there are non-constant fields that are used by the program, initialization code must be run to ensure those fields are assigned a value.
Hope that helps.
P.S.: That chapter is available online here if anyone wants to read it in full.
To cite the Java language specification §12.4.1:
A class or interface type T will be
initialized immediately before the
first occurrence of any one of the
following:
T is a class and an instance of T is created.
T is a class and a static method declared by T is invoked.
A static field declared by T is assigned.
A static field declared by T is used and the reference to the field is not
a compile-time constant (§15.28).
References to compile-time constants
must be resolved at compile time to a
copy of the compile-time constant
value, so uses of such a field never
cause initialization.
Invocation of certain reflective
methods in class Class and in package
java.lang.reflect also causes class or
interface initialization. A class or
interface will not be initialized
under any other circumstance.
The intent here is that a class or interface type has a set of initializers that put it in a consistent state, and that this state is the first state that is observed by other classes.
Interesting. Let's see why superclass must be initialized before subclass.
class A
static x = DB.insert(1,...);
class B extends A
static y = DB.select(1);
The static initializer of a superclass can cause some side effects that the compiler cannot see, and the subclass may depend on such side effects.
However the same argument can apply to super interfaces. I don't see a hard reason why Java doesn't initialize super interfaces eagerly. Soft reasons are anybody's guess.
Give the rules as they are, we must be careful with field initialization in interfaces:
better not have any fields in an interface
otherwise, fields better be compile time constant only
otherwise, field initialization better not have any side effect.
otherwise, side effect must be only accessible through the field itself

Java member object inside class of same type

I am looking at a codebase and I often see something like:
public class SomeClass
{
protected static SomeClass myObject;
//...
public static SomeClass getObject()
{
return myOjbect
}
}
I'd like to make sure I understand the purpose behind this. Is it to ensure one instance of the class gets shared even if it is instantiated multiple times? I am not sure about the vocabulary here, or else I'd search for the answer, so if this pattern has a name, please let me know.
Also, this seems a little chicken-and-egg definition because the class includes an object of the type of the class. Why isn't this actually paradoxical?
Thanks!
This is really only common with the Singleton Pattern where there is only this one instance of the class. While it has its uses, Singleton is over- and misused more often than not (usually to disguise procedural programming as OO). It also occurs very often in example code for Java AWT or Swing, where you typically subclass Frame / JFrame, and create an instance in a main method inside the same class.
Also, this seems a little
chicken-and-egg definition because the
class includes an object of the type
of the class. Why isn't this actually
paradoxical?
Why do you think it is? The class mainly describes what members instances of this type have - but a static member does not belong to an instance, it belongs to the class itself, so it doesn't have anything to do with the "blueprint" role of the class. Static members are really somewhat un-OO because of that.
But even on the instance level you can have references of the same type. For example, an entry in a linked list would typically have two references to the next and previous entries, which are of the same class.
This is called the Singleton design pattern.
You are correct in stating that the purpose is to ensure only one instance of the class gets created.
Wikipedia has a preyty good article on the pattern.
The pattern you mentioned is called "Singleton", but from your code sample it is not clear if this is really what is intended. Due to the fact that the member is protected, I would guess not - if there are subclasses, then there would probably not be a single instance.
It's called Singleton. You ensure the creation of just ONE (1) object of a given class.
You should add a private Constructor, so the only one who create the object is the class.
public class SomeClass
{
// Using private constructor
protected static SomeClass myObject = new SomeClass();
private SomeClass(){
//...
}
public static SomeClass getObject()
{
return myOjbect
}
}
Much much more here, in Wikipedia
You may want to take a look to Factory Pattern
It's not all that uncommon; it can be a good way to implement the Singleton pattern. There can be other uses as well - sometimes you will want a handful - and no more - of objects of a given class; that class is a good place to hang onto them. In the event that you don't want other classes to be able to create objects of this class, it is common to give the class a private constructor as well.
It's not paradoxical, because the compiler can be aware of a reference to the class before it has fully compiled the class. Later - if you like to think of it this way - it can "fill in the blanks".

Categories

Resources