I want to generate a class that extends other class using JavaPoet.
For example I have this class:
#MyAnnotation
public class ClassA {
public ClassA(String paramA, int paramB) {
// some code
}
}
and I want to generate new class like this one:
public class Generated_ClassA extends ClassA {
public Generated_ClassA (String paramA, int paramB) {
super(paramA, paramB);
}
}
However, I don't see any ready-to-use API in JavaPoet to create constructors which are calling superclass constructors. How it is possible to do this and what are the best practices?
You can do it by using MethodSpec.Builder#addStatement
MethodSpec.constructorBuilder()
.addModifiers(Modifier.PUBLIC)
.addParameter(String.class, "paramA")
.addParameter(Integer.TYPE, "paramB")
.addStatement("super(paramA, paramB)")
.build();
You can also also use MethodSpec.Builder#addCode and build same code using CodeBlock.Builder#addStatement but unfortunately AFAIK there is no specific builders available for calling super.
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
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
Let's imagine I implement the following:
public enum ExportAPIForOSGi {
;
public static SpecialObject newSpecialObject() {
return new SpecialObjectImplv1();
}
}
public abstract class SpecialObject {
public abstract String specialMethod(String s);
}
public class SpecialObjectImplv1 extends SpecialObject {
#Override
public String specialMethod(String s) {
return "33" + s;
}
}
Each class is declared in its own separate file. Only ExportAPIForOSGi and SpecialObject are to be OSGi exported.
My question: is it safe to export ExportAPIForOSGi since it contains an explicit reference to implementation code (i.e., SpecialObjectImplv1)? Is the implementation code going to be exposed?
Let's imagine that later, I use SpecialObjectImplv2 in ExportAPIForOSGi instead of v1? Is this going to be an issue?
You need to export the package(s) containing ExportAPIForOSGi and SpecialObject since they are your public API. SpecialObjectImplv1 should be in another package which is not exported. You are then free to change the implementation of newSpecialObject to use another impl class since the impl class is not visible in the signature of the public API.
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