javapoet - how to implement "extends" and "implements" - java

Using Javapoet, how to implement the following:
class A extends class B
class C implements Interface D
In the javadoc, it is mentioned how to create interfaces.

Use TypeSpec.Builder.superclass() for extends, and TypeSpec.Builder.addSuperinterface() for implements.

Suppose you want to generate a Dummy class that extends Exception class and implements the Serializable interface. The generate code is:
...
TypeSpec typeSpec = TypeSpec.classBuilder("Dummy")
.addSuperinterface(Serializable.class)
.superclass(Exception.class)
.build();
JavaFile javaFile = JavaFile.builder("sample.javapoet", typeSpec).build();
...
And the generated code will be:
package sample.javapoet;
import java.io.Serializable;
import java.lang.Exception;
class Hoge extends Exception implements Serializable {
}

Related

I can't use inherited class instead of mother class in generics

Hi suppose this following simple class:
public class CRUDController<T extends __Entity<T>> {
...
}
And
public class Tag extends __Entity<Tag> {
...
}
And
public class KalaTag extends Tag {
...
}
When I use public class TestController extends CRUDController<Tag> everything is ok but when I use public class TestController extends CRUDController<KalaTag> the following error appears:
Type parameter 'KalaTag' is not within its bound; should extend '__Entity < KalaTag >'
What is my problem?
What did I wrong?
Thank you in advance ;)
CRUDController expects its argument (T) to extend __Entity<T>.
Clearly KalaTag does not do it, as it extends __Entity<Tag>.
Possible solutions:
Make KalaTag extend __Entity<KalaTag> directly
Define Tag as class Tag<T> extends __Entity<T> and then class KalaTag extends Tag<KalaTag>
Another options is to allow CRUDController to work with any __Entity bound by parent type of T.
public class CRUDController<T extends __Entity<? super T> > {
}
Again this really depends on your usage of T in CRUDController and its subclasses.

pyjnius java abstract class implementation

I am trying to implement android.bluetooth.le.ScanCallback which is an abstract class using pyjnius. The moment I instantiate the given below python class there is a JVM error. The error states that android.bluetooth.le.ScanCallback is not an interface class. I believe an interface is an abstract class. What am I missing?
class ScanCallback(PythonJavaClass):
__javainterfaces__ = ['android/bluetooth/le/ScanCallback']
def __init__(self, scanCallback, batchCallback=None, errorCallback=None):
super(ScanCallback, self).__init__()
self.batchCallbk = batchCallback
self.scanCallbk = scanCallback
self.errorCallbk = errorCallback
pass
#java_method ('(L/java/utils/List<ScanResult>/)V')
def onBatchScanResults(self,results):
print dir(results)
#java_method ('(I)V')
def onScanFailed(self, errorCode):
print "failed to scan" + str(errorCode)
raise ValueError(str(errorCode))
#java_method ('(IL/android/bluetooth/le/ScanResult)V')
def onScanResult(self, callbackType, result):
print dir(result)
I found out that with PyJNius it is only possible to implement interface class (pure abstract class) not an abstract class. "android/bluetooth/le/ScanCallback" is an abstract class not an interface class which was the case with earlier bluetooth API (< 21).

Java static class import in the declaring class

I have a class like:
package com.example;
public abstract class AbstractClass<S> {
//stuffs
}
Then a class that extends it, and define the generic type as its own inner class:
package com.example2;
import com.example.AbstractClass;
import com.example2.MyObject.MyObjectInnerClass;
public class MyObject extends AbstractClass<MyObjectInnerClass> {
//other stuffs
public static class MyObjectInnerClass {
}
}
Why is needed the import of com.example2.MyObject.MyObjectInnerClass if it stays in the same file?
import com.example.AbstractClass;
import com.example2.MyObject.MyObjectInnerClass;
public class MyObject extends AbstractClass<MyObjectInnerClass> {
It is needed because the nested (not inner) class MyObjectInnerClass only exists with an unqualifed name inside the {, which comes after the use of it in the extendsclause.
A more conventional way of writing it would be:
import com.example.AbstractClass;
public class MyObject extends AbstractClass<MyObject .MyObjectInnerClass> {
Let's start by saying - it's not an inner class, it's a nested class (inner class is a non-static nested class).
That import is needed for two important reasons:
It needs to know which class do you mean - You could also have MyObjectInnerClass as a class in the same package as MyObject. Importless reference to such class would point to exactly that one.
That's what nested classes are for - to group classes in a logical hierarchical structure.
Note that it is customary to, instead of import, write MyObject.MyObjectInnerClass to put emphasis on the relationship between the two.

Could anyone tell me whats use of implements interface which extended with "Serializable" interface with example?

Interface with serializable implements?
public interface SearchCriteria extends Serializable {}
class which implements a interface which doesnt have method initilization
just a extented by "Serializable" interface
public class AbstractSearchCriteria implements SearchCriteria
{
private static final long serialVersionUID = 1L;
private PageCriteria pageCriteria;
public AbstractSearchCriteria()
{
super();
}
public PageCriteria getPageCriteria()
{
return pageCriteria;
}
public void setPageCriteria(PageCriteria pageCriteria)
{
this.pageCriteria = pageCriteria;
}}
serialization is the process of translating data structures or object state into a format that can be stored.
Serializable is a marker interface
serializable is a special interface that specifies that class is serialiazable. It's special in that unlike a normal interface it does not define any methods that must be implemented: it is simply marking the class as serializable.
more here What is object serialization?
In short:
You extended Serializable interface in SearchCriteria interface. All classes that implement the SearchCriteria interface, will also be implementing Serializable interface by default.
For more detailed info check the documentation.

Get all classnames that extend a specific class

In my java project, I need to get a variable from each class that extends another class. My problem here is that I don't know the name of these classes. Let's say my classtree looks like this:
Package
- MyProject
- BaseClass
- Class 1 extends BaseClass
- Class 2 extends BaseClass
- Class 3 extends BaseClass
- Class 4
- Class 5
Now each Class that extends BaseClass has a variable baseVariable, and I need to get its value in MyProject. Is there any way to get a list of classes that extend BaseClass, so I can then access the baseVariable value?
Thanks in advance
You can do this with ClassPath from Guava.
ClassPath cp = ClassPath.from(ClassLoader.getSystemClassLoader());
for (ClassPath.ClassInfo n : cp.getAllClasses()) {
Class cl = n.load();
if (BaseClass.isAssignableFrom(cl)) {
}
}
You could use Reflections:
Set<Class<? extends BaseClass>> subclasses = reflections.getSubTypesOf(BaseClass.class);

Categories

Resources