Cannot extend generic interface in Groovy - oop

I am trying to implement a spring interface called the ObjectPostProcessor interface in groovy to create a new class.
I have tried to do it using a new class implementing the interface and also by creating a new anonymous class. I keep seeing an error saying.
Groovyc: Can't have an abstract method in a non-abstract class.
Which makes me think that groovy doesn't consider the abstract method of the class as overriden correctly.
Below is the code example that is breaking.
What is the correct way to implement this kind of an interface in groovy ?
interface ObjectPostProcessor<T> {
/**
* Initialize the object possibly returning a modified instance that should be used
* instead.
*
* #param object the object to initialize
* #return the initialized version of the object
*/
public <O extends T> O postProcess(O object);
}
// groovy error Error:(15, 1) Groovyc: Can't have an abstract method in a non-abstract class. The class 'ObjectPostProcessorImpl' must be declared abstract or the method 'java.lang.Object postProcess(java.lang.Object)' must be implemented.
class ObjectPostProcessorImpl implements ObjectPostProcessor<Integer> {
#Override
public <O extends Integer> O postProcess(O object) {
return object
}
}
class Anon {
public static void main(String[] args) {
ObjectPostProcessor<Integer> objectPostProcessor = new ObjectPostProcessor<Integer>() {
/** Groovyc: Can't have an abstract method in a
* non-abstract class.
* The class 'ObjectPostProcessorImpl' must
* be declared abstract or the method
* 'java.lang.Object postProcess(java.lang.Object)'
* must be implemented. */
#Override
public <O extends Integer> O postProcess(O object) {
return object;
}
};
ObjectPostProcessorImpl objectPostProcessorImplObj = new ObjectPostProcessorImpl();
System.out.println(objectPostProcessor.postProcess(12));
System.out.println(objectPostProcessorImplObj.postProcess(12));
}
}

Related

Process custom annotation in implementing class of an Resource interface

I am trying to process a custom annotation on a class that implements an external interface that defines a Resource. The setup is the following:
A Resource interface, I can't modify it:
#Path("/v1")
public interface Resource {
#GET
#Path("/foo")
Response foo();
}
An implementation that I can modify:
public class ResourceImpl implements Resource {
#Override
#CustomAnnotation // has Retention.RUNTIME
public Response foo() {
// foo logic
}
}
I've implemented a filter to try and process the #CustomAnnotation on the overriden foo() method:
#Provider
#ServerInterceptor
#Precedence("SECURITY")
public class CustomAnnotationInterceptor implements ContainerRequestFilter {
#Context
ResourceInfo resourceInfo;
#Override
public void filter(ContainerRequestContext containerRequestContext) throws IOException {
// check if the invoked resource method is annotated with #CustomAnnotation and do logic
}
}
However, when I try to get the matched resource class from the ResourceInfo instance, I get the Resource interface, and when I get the matched method, I get the foo() method from the interface which is lacking the #CustomAnnotation. Is there any way around this?
I'm using RESTEasy as an implementation of JAX-RS.
You could implement an interceptor, where you can get hold of the actual resource (method and class) being called. The interceptor should be bound to your annotation using #InterceptorBinding (see 54.2.4 Binding Interceptors to Components).
// Interceptor
#Interceptor
#CustomAnnotation
#Priority(Interceptor.Priority.APPLICATION)
public class CustomAnnotationInterceptor {
#AroundInvoke
public Object interceptCustomAnnotation(InvocationContext ctx) throws Exception {
CustomAnnotation customAnnotation = null;
// The actual method being called
Method method = ctx.getMethod();
if (method != null) {
customAnnotation = method.getAnnotation(CustomAnnotation.class);
}
// ... do stuff with the annotation
return ctx.proceed();
}
}
To get the instance of the class that implements your interface you could use ctx.getMethod().getDeclaringClass() or ctx.getTarget().getClass().getSuperclass().

Using Javassist library to detect runtime type of a method caller

I know that javassist.expr.MethodCall.getClassName() returns the compile time type of the method caller because it depends on bytecode analysis. I am wondering if there is an efficient way to get the actual runtime type of the method caller with javassist using some trick or through code inspection.
Here is a simple example to make things clearer.
public interface Animal {
public void eat();
}
public class Dog implements Animal {
#Override
public void eat() {
System.out.println("dog eating");
}
}
public class MainClass {
public static void main(String[] args) {
Animal a = new Dog();
a.eat();
}
}
In this example, I would like to find a way to get a "Dog" object as the method caller for the method "a.eat()"
From the javassist.expr.MethodCall you can easily get the runtime class that has called this method:
CtClass ctc = javassist.expr.MethodCall.getMethod().getDeclaringClass();
Once you have the Javassist representation of the class that called this method that contains everything you need about this class.
PS if you really need a Dog instance you can use reflection taking the name by the CtClass, e.g.:
Class clazz = Class.forName(ctc.getName());
Dog dog = ((Dog)clazz).newInstance();

Cannot create an instance for Expected Condition class in C# Selenium

When I try to create an instance for Expected Condition class it throws an error
ExpectedConditions obj = new ExpectedConditions();
The error I'm getting here is "Has no Constructors defined".
ExpectedConditions is a sealed class. And the method reside inside the sealed class are static methods.
In C# class, by default there is a constructor. Only the static classes doesn't have a default constructor.
So I have tried a small example
public sealed class A
{
public static string GetName()
{
return "name";
}
public static int GetID()
{
return 1;
}
public string Name()
{
return "aa";
}
}
//Sealed class with static methods
B obj2 = new B();
B.GetName();
B.GetID();
obj2.Name();
Build Succeeded
In my example code, It's possible to create an object for the sealed class and can be able to access the methods.
Why it is not possible to create an object with default constructor
ExpectedConditions obj = new ExpectedConditions();
for the ExpectedCondition class in C# Selenium? Why it is throwing an error when instantiating?
Some notes before:
The sealed modifier is used for a class to prevent other classes to inherit from it.
static classes do have a static constructor that is called automatically to initialize the class before the first instance is created or any static members are referenced. However, the constructor cannot be called directly. You can read more on the topic here.
Now, to get on the subject, you cannot instantiate the ExpectedConditions class because it's constructor is private. You can only use the it's static methods.
An example would be to find an element by ID and wait until it is clickable:
var wait = new WebDriverWait(driver, TimeSpan.FromMinutes(1));
var clickableElement = wait.Until(ExpectedConditions.ElementIsClickable(By.Id("id")));
You can see the implementation of the ExpectedConditions class here.
Github location of the ExpectedConditions class is here.

how to ensure only one instance of singleton class is created?

I have read the concepts of Singleton design pattern and understood that for making a class singleton we have to do the following steps :
1)Private constructor to restrict instantiation of the class from other classes.
2)Private static variable of the same class that is the only instance of the class.
3)Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class.
So my class looks like this :
public class Singleton {
private static Singleton singleton =new Singleton();;
/* A private Constructor prevents any other
* class from instantiating.
*/
private Singleton(){
System.out.println("Creating new now");
}
/* Static 'instance' method */
public static Singleton getInstance( ) {
return singleton;
}
/* Other methods protected by singleton-ness */
public void demoMethod( ) {
System.out.println("demoMethod for singleton");
}
}
But here how we can ensure that only one instance of Singleton is created ? Suppose I have 2 classes Singletondemo1 and Singletondemo2.
In Singletondemo1 , I am calling the getInstance() and craete an object. Same way I can do that in Singletondemo2 also.
So how we will ensure only object is created and also it is thread safe.

design pattern query

i have a question regarding design patterns.
suppose i want to design pig killing factory
so the ways will be
1) catch pig
2)clean pig
3) kill pig
now since these pigs are supplied to me by a truck driver
now if want to design an application how should i proceed
what i have done is
public class killer{
private Pig pig ;
public void catchPig(){ //do something };
public void cleanPig(){ };
public void killPig(){};
}
now iam thing since i know that the steps will be called in catchPig--->cleanPig---->KillPig manner so i should have an abstract class containing these methods and an execute method calling all these 3 methods.
but i can not have instance of abstract class so i am confused how to implement this.
remenber i have to execute this process for all the pigs that comes in truck.
so my question is what design should i select and which design pattern is best to solve such problems .
I would suggest a different approach than what was suggested here before.
I would do something like this:
public abstract class Killer {
protected Pig pig;
protected abstract void catchPig();
protected abstract void cleanPig();
protected abstract void killPig();
public void executeKillPig {
catchPig();
cleanPig();
killPig();
}
}
Each kill will extend Killer class and will have to implement the abstract methods. The executeKillPig() is the same for every sub-class and will always be performed in the order you wanted catch->clean->kill. The abstract methods are protected because they're the inner implementation of the public executeKillPig.
This extends Avi's answer and addresses the comments.
The points of the code:
abstract base class to emphasize IS A relationships
Template pattern to ensure the steps are in the right order
Strategy Pattern - an abstract class is as much a interface (little "i") as much as a Interface (capital "I") is.
Extend the base and not use an interface.
No coupling of concrete classes. Coupling is not an issue of abstract vs interface but rather good design.
public abstract Animal {
public abstract bool Escape(){}
public abstract string SaySomething(){}
}
public Wabbit : Animal {
public override bool Escape() {//wabbit hopping frantically }
public override string SaySomething() { return #"What's Up Doc?"; }
}
public abstract class Killer {
protected Animal food;
protected abstract void Catch(){}
protected abstract void Kill(){}
protected abstract void Clean(){}
protected abstract string Lure(){}
// this method defines the process: the methods and the order of
// those calls. Exactly how to do each individual step is left up to sub classes.
// Even if you define a "PigKiller" interface we need this method
// ** in the base class ** to make sure all Killer's do it right.
// This method is the template (pattern) for subclasses.
protected void FeedTheFamily(Animal somethingTasty) {
food = somethingTasty;
Catch();
Kill();
Clean();
}
}
public class WabbitHunter : Killer {
protected override Catch() { //wabbit catching technique }
protected override Kill() { //wabbit killing technique }
protected override Clean() { //wabbit cleaning technique }
protected override Lure() { return "Come here you wascuhwy wabbit!"; }
}
// client code ********************
public class AHuntingWeWillGo {
Killer hunter;
Animal prey;
public AHuntingWeWillGo (Killer aHunter, Animal aAnimal) {
hunter = aHunter;
prey = aAnimal;
}
public void Hunt() {
if ( !prey.Escape() ) hunter.FeedTheFamily(prey)
}
}
public static void main () {
// look, ma! no coupling. Because we pass in our objects vice
// new them up inside the using classes
Killer ElmerFudd = new WabbitHunter();
Animal BugsBunny = new Wabbit();
AHuntingWeWillGo safari = new AHuntingWeWillGo( ElmerFudd, BugsBunny );
safari.Hunt();
}
The problem you are facing refer to part of OOP called polymorphism
Instead of abstract class i will be using a interface, the difference between interface an abstract class is that interface have only method descriptors, a abstract class can have also method with implementation.
public interface InterfaceOfPigKiller {
void catchPig();
void cleanPig();
void killPig();
}
In the abstract class we implement two of three available methods, because we assume that those operation are common for every future type that will inherit form our class.
public abstract class AbstractPigKiller implements InterfaceOfPigKiller{
private Ping pig;
public void catchPig() {
//the logic of catching pigs.
}
public void cleanPig() {
// the logic of pig cleaning.
}
}
Now we will create two new classes:
AnimalKiller - The person responsible for pig death.
AnimalSaver - The person responsible for pig release.
public class AnimalKiller extends AbstractPigKiller {
public void killPig() {
// The killing operation
}
}
public class AnimalSaver extends AbstractPigKiller {
public void killPing() {
// The operation that will make pig free
}
}
As we have our structure lets see how it will work.
First the method that will execute the sequence:
public void doTheRequiredOperation(InterfaceOfPigKiller killer) {
killer.catchPig();
killer.cleanPig();
killer.killPig();
}
As we see in the parameter we do not use class AnimalKiller or AnimalSever. Instead of that we have the interface. Thank to this operation we can operate on any class that implement used interface.
Example 1:
public void test() {
AnimalKiller aKiller = new AnimalKiller();// We create new instance of class AnimalKiller and assign to variable aKiller with is type of `AnimalKilleraKiller `
AnimalSaver aSaver = new AnimalSaver(); //
doTheRequiredOperation(aKiller);
doTheRequiredOperation(aSaver);
}
Example 2:
public void test() {
InterfaceOfPigKiller aKiller = new AnimalKiller();// We create new instance of class AnimalKiller and assign to variable aKiller with is type of `InterfaceOfPigKiller `
InterfaceOfPigKiller aSaver = new AnimalSaver(); //
doTheRequiredOperation(aKiller);
doTheRequiredOperation(aSaver);
}
The code example 1 and 2 are equally in scope of method doTheRequiredOperation. The difference is that in we assign once type to type and in the second we assign type to interface.
Conclusion
We can not create new object of abstract class or interface but we can assign object to interface or class type.