How to extend a jython class in a java class - java

I would like to extend a jython class in a java class
public class JavaClass extends JythonClass
how do I import the Jython class? Does it have to be compiled? A link to documentation would be already useful.
Example:
class JythonClass(threading.Thread):
def do(self):
print("hallo")
--
public class JavaClass extends JythonClass
{
public void hello()
{ System.out.print("hallo")}
}

You can extend a Jython class in Java such that the result is usable in Jython by creating a Jython class that extends both the Java "subclass" and the Jython "superclass". Let's say you have this Jython class:
class JythonClass(object):
def get_message(self):
return 'hello'
def print_message(self):
print self.get_message()
You can create your Java class, partially, without extending anything:
public class JavaClass {
private String message;
public String get_message() {
return message;
}
protected JavaClass(String message) {
this.message = message;
}
}
And then cause the "extending" relationship in Jython:
from javapackage import JavaClass as _JavaClass
from jythonpackage import JythonClass
class JavaClass(_JavaClass, JythonClass):
pass
Now this will work:
obj = JavaClass('goodbye')
obj.print_message()
If instead you wish to extend a Jython class in Java, and use it like a normal Java class, the easiest way would be to use composition, instead of inheritance:
create a Java interface for the methods on your Jython class
make your Jython class extend the Java interface (either by directly modifying your Jython class code, or by something like what I explained above)
create your Java subclass as implementing the interface, with an instance of the Jython "superclass" as a private field
any method in your Java subclass that you don't wish to override, just call that method on the private Jython instance

I think that this is covered by Ch10 of The Definitive Guide to Jython
In this example the author uses an interface BuildingType this can be changed to an abstract class
public abstract class BuildingType {
public abstract String getBuildingName();
public abstract String getBuildingAddress();
public abstract String getBuildingId();
#Override
public String toString(){
return "Abstract Building Info: " +
getBuildingId() + " " +
getBuildingName() + " " +
getBuildingAddress();
}
}
which you can extend with your own methods, in this case I have added toString() and used it in 'print' instead of the authors original code:
public class Main {
private static void print(BuildingType building) {
System.out.println(building.toString());
}
public static void main(String[] args) {
BuildingFactory factory = new BuildingFactory();
BuildingType building1 = factory.create("BUILDING-A", "100 WEST MAIN", "1")
print(building1);
BuildingType building2 = factory.create("BUILDING-B", "110 WEST MAIN", "2");
print(building2);
BuildingType building3 = factory.create("BUILDING-C", "120 WEST MAIN", "3");
print(building3);
}
}
You can duplicate this code using the code from CH10 of the The Definitive Guide to Jython and all credit must go to the author - I've only changed the Interface into a Abstract class.
You coluld also consider using a Java 7 Default method in the interface

Related

Java ASM dynamic class inheritance

Using ASM 9 on Java11, I am able to generate my Sample Class dynamically, but my current class implements interface MyBeanIface
public class Sample implements MYBeanIface
{
public String SampleId = "";
public Sample() {
this.super();
}
// other getters/setters
}
I want to know how do i implement all methods from interface using ASM?
Also want to know if there is any way to generate toString() method dynamically?
Thanks

Strange Java serialization issue

I have a simple java abstract class:
abstract public class MyClass implements Streamable {
private static final long serialVersionUID = 5593048244217796061L;
...
protected MyClass() { }
...
abstract public ReturnType abstractMethod(ArgType crd);}
All types mentioned are also streamable (i'm not using default Java serialization, but some "GWT" serializer).
Now, i have A LOT of classes which work like this:
public abstract class AnotherClass implements Streamable {
protected AnotherClass() { }
protected void initDeterminators() {
MyClass determinator = new MyClass(conditions) {
#Override
public ReturnType abstractMethod(ArgType crd) {
//some code
}
};
addDeterminator(determinator);
}}
While serializing the "AnotherClass" i'm getting an error:
com.nkdata.gwt.streamer.client.StreamerException: Error creating streamer for class package.AnotherClass$1
Adding "Serial UIID" didn't help. "MyClass" do have protected default ctor. What should i do in order to make it serializable? Can i avoid changing all those other classes which make use of "MyClass"?
It turned out i had some cross references i didn't mentioned for sake of simplicity:
in place of
//some code
i was calling the method of outer "AnotherClass" instance and it seems that's a no-no for serialization.
I've solved by:
1) avoiding anonymous class
2) passing "conditions" and "this" to the constructor of that class.
3) instead of
>some code calling outer method<
i've did
>some code calling "parent.method()"<

Java function (method) available everywhere (global)

I've recently (4 days ago) started programming in JAVA. I have some overall programming experience from C++ and PHP. My question is: can we implement a function in JAVA, that is available in all classes? I'm thinking of some global logging function, that I need to call in several places (log events, errors, etc.).
Imagine I have two classes, A and B. I need to call logging function in both of them, but I don't want to copy whole function body (awful thing I believe), and I want to call it strict (without creating another class, instantiating it, and then calling from the instance), like logEvent(someVariable). So I should use an abstract class C, which A and B will extend, BUT they are already an extension of other class (built-in). Since multiple inheritance isn't allowed (is it?), I need to do some trick. Singleton is not pleasing me too. In PHP or C++ I would just create separate file with function body and then include it.
Here is how I want to use it:
public class A extends SomeClass {
String error = "Error from class A";
logEvent(error);
}
public class B extends SomeOtherClass {
String error = "Error from class B";
logEvent(error);
}
Put a static method in any class (it could be a utils class, or whatever), then call it like this: ClassName.functionName()
Static methods belong to the class, not instances of the class, so you don't need to instantiate the class to access the method
But everything in Java has to be in a class, so you can't access it without the class name.
You should use static method:
package xxx;
public class Util{
public static void logEvent(String error){
...
}
}
and import static:
import static xxx.Util.*;
public class A extends SomeClass {
String error = "Error from class A";
logEvent(error);
}
You may use static method.
Define a class with a static method:
public class Util{
public static void logEvent(String error){
...
}
}
Then, you can use static metod like this way:
public class A extends SomeClass {
String error = "Error from class A";
Util.logEvent(error);
}
you may take a look here to learn more about static method, http://www.leepoint.net/notes-java/flow/methods/50static-methods.html

How to access method from two classes which do not share an interface?

I am creating a java library that will access web services, but the library will be called in different platforms, so we are using ksoap2 and ksoap2-android to generate helper classes for the different platforms. The problem is that we then have two sets of generated classes/methods whose signatures are equivalent, but which do not overtly share a Java Interface - so I can't figure a way to call them from my main code.
A simplified example:
//generated for Android
class A {
public String sayHi() {
return "Hi A";
}
}
//generated for j2se
class B {
public String sayHi() {
return "Hi B";
}
}
//main code - don't know how to do this
XXX talker = TalkerFactory.getInstance()
String greeting = talker.sayHi()
Of course, that last part is pseudo-code. Specifically, how can I call sayHi() on an instance of an object which I don't know the type of at compile time, and which does not conform to a specific interface? My hope is that there is some way to do this without hand editing all of the generated classes to add an "implements iTalker".
The straightforward way is to use an adapter.
interface Hi {
void sayHi();
}
public static Hi asHi(final A target) {
return new Hi() { public void sayHi() { // More concise from Java SE 8...
target.sayHi();
}};
}
public static Hi asHi(final B target) {
return new Hi() { public void sayHi() { // More concise from Java SE 8...
target.sayHi();
}};
}
In some circumstance it may be possible, but probably a bad idea and certainly less flexible, to subclass and add in the interface.
public class HiA extends A implements Hi {
}
public class HiB extends B implements Hi {
}

Interfaces in Java: cannot make implemented methods protected or private

I know that an interface must be public. However, I don't want that.
I want my implemented methods to only be accessible from their own package, so I want my implemented methods to be protected.
The problem is I can't make the interface or the implemented methods protected.
What is a work around? Is there a design pattern that pertains to this problem?
From the Java guide, an abstract class wouldn't do the job either.
read this.
"The public access specifier indicates that the interface can be used by any class in any package. If you do not specify that the interface is public, your interface will be accessible only to classes defined in the same package as the interface."
Is that what you want?
You class can use package protection and still implement an interface:
class Foo implements Runnable
{
public void run()
{
}
}
If you want some methods to be protected / package and others not, it sounds like your classes have more than one responsibility, and should be split into multiple.
Edit after reading comments to this and other responses:
If your are somehow thinking that the visibility of a method affects the ability to invoke that method, think again. Without going to extremes, you cannot prevent someone from using reflection to identify your class' methods and invoke them. However, this is a non-issue: unless someone is trying to crack your code, they're not going to invoke random methods.
Instead, think of private / protected methods as defining a contract for subclasses, and use interfaces to define the contract with the outside world.
Oh, and to the person who decided my example should use K&R bracing: if it's specified in the Terms of Service, sure. Otherwise, can't you find anything better to do with your time?
When I have butted up against this I use a package accessible inner or nested class to implement the interface, pushing the implemented method out of the public class.
Usually it's because I have a class with a specific public API which must implement something else to get it's job done (quite often because the something else was a callback disguised as an interface <grin>) - this happens a lot with things like Comparable. I don't want the public API polluted with the (forced public) interface implementation.
Hope this helps.
Also, if you truly want the methods accessed only by the package, you don't want the protected scope specifier, you want the default (omitted) scope specifier. Using protected will, of course, allow subclasses to see the methods.
BTW, I think that the reason interface methods are inferred to be public is because it is very much the exception to have an interface which is only implemented by classes in the same package; they are very much most often invoked by something in another package, which means they need to be public.
This question is based on a wrong statement:
I know that an interface must be public
Not really, you can have interfaces with default access modifier.
The problem is I can't make the interface or the implemented methods protected
Here it is:
C:\oreyes\cosas\java\interfaces>type a\*.java
a\Inter.java
package a;
interface Inter {
public void face();
}
a\Face.java
package a;
class Face implements Inter {
public void face() {
System.out.println( "face" );
}
}
C:\oreyes\cosas\java\interfaces>type b\*.java
b\Test.java
package b;
import a.Inter;
import a.Face;
public class Test {
public static void main( String [] args ) {
Inter inter = new Face();
inter.face();
}
}
C:\oreyes\cosas\java\interfaces>javac -d . a\*.java b\Test.java
b\Test.java:2: a.Inter is not public in a; cannot be accessed from outside package
import a.Inter;
^
b\Test.java:3: a.Face is not public in a; cannot be accessed from outside package
import a.Face;
^
b\Test.java:7: cannot find symbol
symbol : class Inter
location: class b.Test
Inter inter = new Face();
^
b\Test.java:7: cannot find symbol
symbol : class Face
location: class b.Test
Inter inter = new Face();
^
4 errors
C:\oreyes\cosas\java\interfaces>
Hence, achieving what you wanted, prevent interface and class usage outside of the package.
Here's how it could be done using abstract classes.
The only inconvenient is that it makes you "subclass".
As per the java guide, you should follow that advice "most" of the times, but I think in this situation it will be ok.
public abstract class Ab {
protected abstract void method();
abstract void otherMethod();
public static void main( String [] args ) {
Ab a = new AbImpl();
a.method();
a.otherMethod();
}
}
class AbImpl extends Ab {
protected void method(){
System.out.println( "method invoked from: " + this.getClass().getName() );
}
void otherMethod(){
System.out.println("This time \"default\" access from: " + this.getClass().getName() );
}
}
Here's another solution, inspired by the C++ Pimpl idiom.
If you want to implement an interface, but don't want that implementation to be public, you can create a composed object of an anonymous inner class that implements the interface.
Here's an example. Let's say you have this interface:
public interface Iface {
public void doSomething();
}
You create an object of the Iface type, and put your implementation in there:
public class IfaceUser {
private int someValue;
// Here's our implementor
private Iface impl = new Iface() {
public void doSomething() {
someValue++;
}
};
}
Whenever you need to invoke doSomething(), you invoke it on your composed impl object.
I just came across this trying to build a protected method with the intention of it only being used in a test case. I wanted to delete test data that I had stuffed into a DB table. In any case I was inspired by #Karl Giesing's post. Unfortunately it did not work. I did figure a way to make it work using a protected inner class.
The interface:
package foo;
interface SomeProtectedFoo {
int doSomeFoo();
}
Then the inner class defined as protected in public class:
package foo;
public class MyFoo implements SomePublicFoo {
// public stuff
protected class ProtectedFoo implements SomeProtectedFoo {
public int doSomeFoo() { ... }
}
protected ProtectedFoo pFoo;
protected ProtectedFoo gimmeFoo() {
return new ProtectedFoo();
}
}
You can then access the protected method only from other classes in the same package, as my test code was as show:
package foo;
public class FooTest {
MyFoo myFoo = new MyFoo();
void doProtectedFoo() {
myFoo.pFoo = myFoo.gimmeFoo();
myFoo.pFoo.doSomeFoo();
}
}
A little late for the original poster, but hey, I just found it. :D
You can go with encapsulation instead of inheritance.
That is, create your class (which won't inherit anything) and in it, have an instance of the object you want to extend.
Then you can expose only what you want.
The obvious disadvantage of this is that you must explicitly pass-through methods for everything you want exposed. And it won't be a subclass...
I would just create an abstract class. There is no harm in it.
With an interface you want to define methods that can be exposed by a variety of implementing classes.
Having an interface with protected methods just wouldn't serve that purpose.
I am guessing your problem can be solved by redesigning your class hierarchy.
One way to get around this is (depending on the situation) to just make an anonymous inner class that implements the interface that has protected or private scope. For example:
public class Foo {
interface Callback {
void hiddenMethod();
}
public Foo(Callback callback) {
}
}
Then in the user of Foo:
public class Bar {
private Foo.Callback callback = new Foo.Callback() {
#Override public void hiddenMethod() { ... }
};
private Foo foo = new Foo(callback);
}
This saves you from having the following:
public class Bar implements Foo.Callback {
private Foo foo = new Foo(this);
// uh-oh! the method is public!
#Override public void hiddenMethod() { ... }
}
I think u can use it now with Java 9 release. From the openJdk notes for Java 9,
Support for private methods in interfaces was briefly in consideration
for inclusion in Java SE 8 as part of the effort to add support for
Lambda Expressions, but was withdrawn to enable better focus on higher
priority tasks for Java SE 8. It is now proposed that support for
private interface methods be undertaken thereby enabling non abstract
methods of an interface to share code between them.
refer https://bugs.openjdk.java.net/browse/JDK-8071453

Categories