passing the data to the controller - java

when i run that time,this error will be produced.
500 Could not instantiate bean class
[org.broadleafcommerce.core.catalog.service.CatalogService]: Specified
class is an interface

Somewhere, you are doing a
new CatalogService();
Since it is an interface, you can create objects out of it but of some class that implements that interface. You can do:
public class MyCatalogService implements CatalogService {
...
}
and
CatalogService cs = new MyCatalogService();
Read a little more about Java classes, interfaces and inheritance. Ah, and this question was easy; but if you want answers you will probably need to add more detail to your questions.

Related

Bind default implementation in case of multiple implementation in Guice

I have class hierarchy as follows:
interface Pen{}
class SimplePen implements Pen{}
class ComplexPen implements Pen{}
Code using this is as follows
class A{
public A(Pen pen){}
}
class B{
public B(ComplexPen pen){}
}
So what i want to do is, by default Pen should be bound to SimplePen and ComplexPen should be bound only when asked explicitly as in case of class B.
bind(Pen.class).to(SimplePen.class).in(Singleton.class)
bind(ComplexPen.class)
The above Guice config fails at runtime saying implementation of Pen already bound. How do i go about this?
Note am trying to avoid .annotatedWith(Names.named("complexPen"))
My bad, the code i gave works. I had some extra code which was creating more bindings.
bind(Pen.class).to(SimplePen.class).in(Singleton.class)
bind(ComplexPen.class)

How do I correctly generate a dynamic proxy class that's based on the right class?

I have an interface defined as follows:
public interface Cache {
}
Then an abstract class implementing the above:
public abstract class AbstractCache implements Cache {
}
Then a concrete class inheriting from above:
public class RealTimeCache extends AbstractCache {
}
Then another class defined as follows:
public class CacheProbe {
public static <T> T probe(T base) {
return (T) Proxy.newProxyInstance(
base.getClass().getClassLoader(),
new Class[]{Cache.class},
new MethodCountInvocationHandler(base) // I am not mentioning this class as it's irrelevant
);
}
}
I have a class as follows which is using all of the above:
public class CacheLoader<T extends Cache> {
public T load() {
T result = getResult(...);
CacheProbe x = new CacheProbe(result);
return x.probe();
}
}
Lastly, the lines causing the issue (located outside above classes):
final CacheLoader<RealTimeCache> cacheLoader = getNewLoader(); //Method of this method is irrelevant and unchangeable
RealTimeCache x = cacheLoader.load(); //This is the line which is causing a runtime issue
Problem is, at run time the following exception is thrown at the last line mentioned above:
java.lang.ClassCastException: com.sun.proxy.$Proxy57 cannot be cast to RealTimeCache
However I don't see how this is possible because the dynamic proxy class generated is based on Cache.
How do I fix this ?
Please note that I can only change CacheProbe class in order to fix this. Cache, AbstractCache, RealTimeCache, CacheLoader and those last two lines are unchangeable.
However I don't see how this is possible because the dynamic proxy class generated is based on Cache.
Yes, the docs for java.lang.reflect.Proxy say
Proxy provides static methods for creating dynamic proxy classes and instances, and it is also the superclass of all dynamic proxy classes created by those methods.
(emphasis added)
Thus, you cannot use Proxy to create (an instance of) a subclass of an arbitrary class of your choice.
How do I fix this ?
You can create an ordinary subclass of RealTimeCache, and return an instance of that. Proxy is meant primarily to serve for interfaces that are not known until runtime, and in that case the only way to interact with them anyway is the interface type. That's not your scenario.
If necessary, you can implement such a subclass in terms of a MethodCountInvocationHandler, just as your proxy class uses, but I'm sure it would be easier to implement whatever tooling that is supposed to provide directly.

How to instantiate a Java abstract class with a constructor parameter with a groovy closure

I am trying to instantiate a Java abstract class from my Groovy code. Considering the following Java abstract class (non relevant processing is stripped out from the class):
public abstract class StackOverflow{
public abstract String answerMe();
}
I can easily instantiate it in Groovy this way, and the call to answerMe() will trigger the correct output:
StackOverflow stack = [answerMe : { "Answer" }] as StackOverflow
Now if I modify the StackOverflow class adding a String parameter in the constructor like this :
public abstract class StackOverflowStr{
public StackOverflowStr(String s){}
public abstract String answerMe();
}
I don't really know how to instantiate my object, I tried a lot of thing, but I can't seem to find the right syntax, does someone got any clue ?
You can instantiate it in classic Java style:
StackOverflowStr stack = new StackOverflowStr("javaish"){
String answerMe() {"answer"}
}
Just for the record, and to be clear on wording: in all of these scenarios, you're not instantiating an abstract class.
Abstract classes are classes that can never be instantiated.
You're instantiating a concrete anonymous class that extends an abstract class. B-)

can't cast to implemented interface

i'm very confused...
I have a class which directly implements an interface:
public class Device implements AutocompleteResult
{...}
Here is proof that I'm looking at the right variables:
Object match = ...;
log.debug(match.getClass()); // Outputs 'Device'
log.debug(match.getClass().getInterfaces()[0]); // Outputs 'AutocompleteResult'
Yet when I try to cast an instance of the class to the interface:
AutocompleteResult result = (AutocompleteResult) match;
I get a ClassCastException!
ClassCastException: Device cannot be cast to AutocompleteResult
Also, isAssignableFrom returns false and i'm not sure why:
log.debug(AutocompleteResult.class.isAssignableFrom(Device.class));
from the doc:
Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter.
Shouldn't I always be able to cast a object to an interface its class implements?
Thanks.
This can happen if two different classloaders load a class named AutocompleteResult.
These two classes are then treated as entirely different classes, even if they have the same package and name (and even implementation/fields/methods).
A common cause for this is if you use some kind of plugin system and both your base classes and the plugin classes provide the same class.
To check for this issue print the value returned by Class.getClassLoader() on both offending classes (i.e. the class of the interface implemented by Device and the result of AutocompleteResult.class).
AKA when Java apparently doesn't Java.
I hit this problem recently with Play Framework 2.6.3, what helped me was this:
https://www.playframework.com/documentation/2.6.x/ThreadPools#Application-class-loader
I leave this info here for the people that might have the same problem.
To make it clearer, what helps is:
Injecting Application on an Eager Singleton and then using its classloader to load the classes I was having issues with.
To make it clearer
public class Module {
#Override
public void configure {
bind(TheClassLoaderLoader.class).asEagerSingleton()
public static class TheClassLoaderLoader {
#Inject
public TheClassLoaderLoader( Application application) {
ClassLoader classloader = application.classloader();
Class<?> interfaceClass = classloader.loadClass(InterfaceClass.class.getName());
classloader.loadClass(ImplementsInterfaceClass.class.getName()).asSubclass(interfaceClass);
The example here https://playframework.com/documentation/2.6.x/JavaDependencyInjection#Configurable-bindings
That uses Environment often throws a frustrating ClassNotFoundException
Cheers

ClassCastException when trying to create Proxy object

I'm trying to create a proxy for a given Runnable object using the following code:
public class WorkInvocationHandler implements InvocationHandler {
public static Runnable newProxyInstance(Runnable work)
{
return (Runnable)java.lang.reflect.Proxy.newProxyInstance(
work.getClass().getClassLoader(),
getInterfacesWithMarker(work),
new WorkInvocationHandler(work));
}
private static Class[] getInterfacesWithMarker(Runnable work)
{
List allInterfaces = new ArrayList();
// add direct interfaces
allInterfaces.addAll(Arrays.asList(work.getClass().getInterfaces()));
// add interfaces of super classes
Class superClass = work.getClass().getSuperclass();
while (!superClass.equals(Object.class))
{
allInterfaces.addAll(Arrays.asList(superClass.getInterfaces()));
superClass = superClass.getClass().getSuperclass();
}
// add marker interface
allInterfaces.add(IWorkProxy.class);
return (Class [])allInterfaces.toArray(new Class[allInterfaces.size()]);
}
}
The proxy should implement all interfaces that the given object implements with the additional marker interface that indicates whether the proxy was already created.
Since I don't know for sure that the given object implements Runnable directly I traverse also on all super classes, however I assume that if it implements another interface that implements Runnable it will work so I don't need to traverse also on interfaces hierarchy.
However, I still get ClassCastException when trying to cast the proxy to Runnable:
java.lang.ClassCastException: $Proxy24 incompatible with java.lang.Runnable
I'm trying to think what could cause this exception. The class hierarchy of the given object is not available.
Any ideas ?
UPDATE removed useless code.
This is not the problem, but you should use a Set<Class<?>> when you gather all the interfaces because you can get duplicates of the same interface in the hierarchy.
Your code to walk the super classes is wrong. Replace
superClass = superClass.getClass().getSuperclass();
with
superClass = superClass.getSuperclass();
Otherwise you'll quickly take a detour to java.lang.Class and then to java.lang.Object.

Categories