im dealing with a codebase that has builds MBeans (for export to jmx).
the original code simply builds an MBeanInfo instance:
#Override
public MBeanInfo getMBeanInfo() {
MBeanAttributeInfo[] attrs = //SLOW TO BUILD
return new MBeanInfo(...attrs...);
}
since the mbean attributes are expensive to build, and this method get called rather frequently (even with no jmx clients attached), i've tried creating a subclass of MBeanInto that lazily calculates those attributes:
public class LazyMBeanInfo extends MBeanInfo implements Externalizable {
private transient AttributeCallback callback = null;
private volatile MBeanAttributeInfo[] lazyAttrs = null;
public LazyMBeanInfo(...AttributeCallback callback...) throws IllegalArgumentException {
super(className, description, null, constructors, operations, notifications);
this.callback = callback;
}
#Override
public MBeanAttributeInfo[] getAttributes() {
MBeanAttributeInfo[] val = lazyAttrs;
if (val != null) {
return val.clone(); //match upstream behaviour
}
if (callback == null) {
throw new IllegalStateException("BUG");
}
val = callback.buildAttributes();
if (val == null) {
val = new MBeanAttributeInfo[0];
}
lazyAttrs = val;
return val.clone();
}
public interface AttributeCallback {
MBeanAttributeInfo[] buildAttributes();
}
}
the problem is that JMX (over RMI) serializes the MBeanInfo object, and then in jconsole (or jvisualVM) i get an error:
so - can i somehow implement Externalizable and serialize myself as an instance of the parent class? ideally i'd like this to work:
public class LazyMBeanInfo extends MBeanInfo implements Externalizable {
//same as before, plus:
#Override
public void writeExternal(ObjectOutput out) throws IOException {
MBeanInfo vanilla = new MBeanInfo(...);
out.writeObject(vanilla);
}
}
but it doesnt.
is this possible somehow ?
Unless you are using [highly dynamic] DynamicMBeans, I don't see why the MBeanInfo needs to be rebuilt for every call to getMBeanInfo(), but ....
Your LazyMBeanInfo can be made to work (though I have not tested this specific case). MBeanInfo already implements Serializable, so what you want is for the serialization process to write out an MBeanInfo, not a LazyMBeanInfo, since the client probably doesn't have that class in its classpath. However, LazyMBeanInfo can implement this method:
Object writeReplace() throws ObjectStreamException;
at which point you write out the underlying MBeanInfo. See the Serializable JavaDoc, specifically:
Serializable classes that need to designate an alternative object to
be used when writing an object to the stream should implement this
special method with the exact signature:
ANY-ACCESS-MODIFIER Object writeReplace() throws
ObjectStreamException;
In that way, the actual object can be an instance of LazyMBeanInfo, but what you write out can be an actual MBeanInfo, built from your cached lazyAttrs.
Having said that, rather than implementing a build-on-first-call approach, I would implement a build-before-first-use by simply building the full MBeanInfo when the MBean is first created, or when the MBean is registered. Then just return the pre-built MBeanInfo on each getMBeanInfo() call.
To do this at MBean registration time, implement the MBeanRegistration interface, and build the cached MBeanInfo in the postRegister method.
Related
I have a bit of code that requires a copy of an object be sent in. This requirement is because a service (runtime library) that is called modifies the object sent. This object also needs to expose setters, in case the doThing method below needs to set any field in the ImportantObj class. This implementation is pending change, but does not have a reasonable expectation to be changed in the near future. My workaround is to provide a class that does as follows:
public class DangerousCallWrapper<T> implements DangerousCaller<T> {
public T doThing(T dataObject) {
T cloneOfDataObject = #Clone of dataObject
// This service modifies the cloneOfDataObject... dangerous!
Optional<T> result = service.doThing(cloneOfDataObject);
return result.orElseThrow(() -> new RuntimeException("No data object returned");
}
}
public interface DangerousCaller<T> {
/**
* Performs the functionality of the DangerousService
*/
public T doThing(T);
}
public DangerousService<T> {
public T doThing(T data) {
data.importantField = null;
data.thing = "Done!";
return data;
}
}
public static void main() {
DangerousService service = new DangerousService<ImportantObj>();
ImportantObj important = new ImportantObj().setImportantField("Password for my bank account").setThing("Undone");
service.doThing(important);
//would fail this check
assertNotNull(important.importantField);
DangerousCallWrapper wrapper = new DangerousCallWrapper<ImportantObj>();
ImportantObj important = new ImportantObj().setImportantField("Password for my bank account").setThing("Undone");
service.doThing(important);
//would not fail this check
assertNotNull(important.importantField);
}
So the first line of that method is where I am stuck. It is a generic type, so I can't explicitly call some cloning utility like Jackson, or similar.
So I thought I would just add T extends Cloneable to the method... but I opened the can of worms that Cloneable is beyond taboo (https://www.artima.com/intv/bloch13.html). I have also read that copy constructors are probably the best way to handle this... However, I am unsure of how to denote that using the generics.
So my thought was to provide an interface Copyable that does what you would expect Cloneable to do: expose a method, copy() that will create a new instance of the class.
Does this constitute a viable approach?
To solve your problem you need to polymorphically make a copy of dataObject like this:
T cloneOfDataObject = dataObject.clone();
and the issue is that Cloneable does not have a clone() method, so the above does not compile.
Given this premise, it does make sense to create your own Copyable interface that defines a clone() method so you can leverage already-implemented clone() methods (if they exist) on the classes of your data object. For maximum effectiveness this interface would need to be generic as well:
interface Copyable<T> {
public T clone();
}
and the type bound:
public class DangerousCallWrapper<T extends Copyable<T>>
implements DangerousCaller<T> {
I have a public abstract class java.nio.ByteBuffer instance which is actually an instance of private class java.nio.HeapByteBuffer and I need to make a proxy object which would call some invocation method handler to check access permissions and then call the invoked method on the actual instance.
The problem is that the java.nio.ByteBuffer class has only private constructors and also has some final methods, thus I can not create proxy instances with javassist.util.proxy.ProxyFactory class.
So, how can I make a proxy object to control the invocation of a java.nio.ByteBuffer instance including those final methods invocation?
Please be aware that I am presenting a solution based on my own (FOSS) framework Byte Buddy which is however already mentioned as a potential solution in one of the comments.
Here is a simple proxy approach which creates a subclass. First, we introduce a type for creating proxies for ByteBuffers:
interface ByteBufferProxy {
ByteBuffer getOriginal();
void setOriginal(ByteBuffer byteBuffer);
}
Furthermore, we need to introduce an interceptor to use with a MethodDelegation:
class Interceptor {
#RuntimeType
public static Object intercept(#Origin(cacheMethod = true) Method method,
#This ByteBufferProxy proxy,
#AllArguments Object[] arguments)
throws Exception {
// Do stuff here such as:
System.out.println("Calling " + method + " on " + proxy.getOriginal());
return method.invoke(proxy.getOriginal(), arguments);
}
}
This interceptor is capable of intercepting any method as the #RuntimeType casts the return type in case that it does not fit the Object signature. As you are merely delegating, you are safe. Plase read the documentation for details. As you can see from the annotations, this interceptor is only applicable for instances of ByteBufferProxy. Bases on this assumption, we want to:
Create a subclass of ByteBuffer.
Add a field to store the original (proxied) instance.
Implement ByteBufferProxy and implement the interface methods to access the field for the stored instance.
Override all other methods to call the interceptor that we defined above.
This we can do as follows:
#Test
public void testProxyExample() throws Exception {
// Create proxy type.
Class<? extends ByteBuffer> proxyType = new ByteBuddy()
.subclass(ByteBuffer.class)
.method(any()).intercept(MethodDelegation.to(Interceptor.class))
.defineField("original", ByteBuffer.class, Visibility.PRIVATE)
.implement(ByteBufferProxy.class).intercept(FieldAccessor.ofBeanProperty())
.make()
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
// Create fake constructor, works only on HotSpot. (Use Objenesis!)
Constructor<? extends ByteBufferProxy> constructor = ReflectionFactory
.getReflectionFactory()
.newConstructorForSerialization(proxyType,
Object.class.getDeclaredConstructor());
// Create a random instance which we want to proxy.
ByteBuffer byteBuffer = ByteBuffer.allocate(42);
// Create a proxy and set its proxied instance.
ByteBufferProxy proxy = constructor.newInstance();
proxy.setOriginal(byteBuffer);
// Example: demonstrates interception.
((ByteBuffer) proxy).get();
}
final methods are obviously not intercepted. However as the final methods in ByteBuffer only serve as convenience methods (e.g. put(byte[]) calls put(byte[],int,int) with the additional arguments 0 and the array length), you are still able to intercept any method invocation eventually as these "most general" methods are still overridable. You could even trace the original invocation via Thread.currentCallStack().
Byte Buddy normally copies all constructors of its super class if you do not specify another ConstructorStrategy. With no accessible constructor, it simply creates a class without constructors what is perfectly legal in the Java class file format. You cannot define a constructor because, by definition, this constructor would need to call another constructor what is impossible. If you defined a constructor without this property, you would get a VerifierError as long as you do not disable the verifier altogether (what is a terrible solution as it makes Java intrinsically unsafe to run).
Instead, for instantiation, we call a popular trick that is used by many mocking frameworks but which requires an internal call into the JVM. Note that you should probably use a library such as Objenesis instead of directly using the ReflectionFactory because Objenesis is more robust when code is run on a different JVM than HotSpot. Also, rather use this in non-prduction code. Do however not worry about performance. When using a reflective Method that can be cached by Byte Buddy for you (via cacheMethod = true), the just-in-time compiler takes care of the rest and there is basically no performance overhead (see the benchmark on bytebuddy.net for details.) While reflective lookup is expensive, reflective invocation is not.
I just released Byte Buddy version 0.3 and I am currently working on documentation. In Byte Buddy 0.4, I plan to introduce an agent builder which allows you to redefine classes during load-time without knowing a thing about agents or byte code.
I can suggest you 2 solutions.
First, simple, not universal, but probably useful for you.
As far as I can see ByteBuffer has several package-private constructors that allow its subclassing and the following final methods:
public final ByteBuffer put(byte[] src) {
public final boolean hasArray() {
public final byte[] array() {
public final int arrayOffset() {
public final ByteOrder order() {
ByteBuffer extends Buffer that declares some of these methods:
public final boolean hasArray() {
public final Object array() {
public final int arrayOffset() {
As you can see, put() and order() are absent here, return type of array() is a little bit confusing, but still can be used.
So, if you use only these 3 methods you can subclass Buffer and create universal wrapper that wraps any other Buffer including ByteBuffers. If you want you can use javaassist's proxy although IMHO it is not necessarily here.
Second, more universal but more tricky solution. You can create agent that removes final modifiers from speicific class (ByteBuffer in your case) during class loading. Then you can create javassist proxy.
Variation of second solution is following. Copy ByteBuffer soruce code to separate project. Remove final modifiers and compile it. Then push it into bootstrap classpath. This solutions is probably easier than second.
Good luck anyway.
Thanks to #raphw I have managed to make a proxy object construction class which makes a proxy for java.nio.ByteBuffer but that class has final methods which I can not overcome and they are extensively used in the required code, those final methods are Buffer.remaining() and Buffer.hasRemaining(), thus they just can not be proxy mapped.
But I would like to share the classes I have made, just as a report.
public final class CacheReusableCheckerUtils {
private static ByteBuddy buddy = new ByteBuddy();
private static Objenesis objenesis = new ObjenesisStd();
public static <T> T createChecker(T object) {
return createChecker(new CacheReusableCheckerInterceptor<>(object));
}
public static <T> T createChecker(CacheReusableCheckerInterceptor<T> interceptor) {
return objenesis.getInstantiatorOf(createCheckerClass(interceptor)).newInstance();
}
private static <T> Class<? extends T> createCheckerClass(CacheReusableCheckerInterceptor<T> interceptor) {
Class<T> objectClass = interceptor.getObjectClass();
Builder<? extends T> builder = buddy.subclass(objectClass);
builder = builder.implement(CacheReusableChecker.class).intercept(StubMethod.INSTANCE);
builder = builder.method(MethodMatchers.any()).intercept(MethodDelegation.to(interceptor));
return builder.make().load(getClassLoader(objectClass, interceptor), Default.WRAPPER).getLoaded();
}
private static <T> ClassLoader getClassLoader(Class<T> objectClass, CacheReusableCheckerInterceptor<T> interceptor) {
ClassLoader classLoader = objectClass.getClassLoader();
if (classLoader == null) {
return interceptor.getClass().getClassLoader();
} else {
return classLoader;
}
}
}
public class CacheReusableCheckerInterceptor<T> {
private T object;
private boolean allowAccess;
private Throwable denyThrowable;
public CacheReusableCheckerInterceptor(#NotNull T object) {
this.object = object;
}
#SuppressWarnings("unchecked")
public Class<T> getObjectClass() {
return (Class<T>) object.getClass();
}
#RuntimeType
public final Object intercept(#Origin(cacheMethod = true) Method method, #This T proxy, #AllArguments Object[] arguments) {
try {
switch (method.getName()) {
case "allowAccess":
allowAccess();
return null;
case "denyAccess":
denyAccess();
return null;
default:
return invokeMethod(method, arguments);
}
} catch (Exception e) {
throw new CacheReusableCheckerException(method, object, proxy, e);
}
}
private Object invokeMethod(Method method, Object[] arguments) throws IllegalAccessException, InvocationTargetException {
checkMethodAccess(method.getName());
return method.invoke(object, arguments);
}
private void allowAccess() {
if (allowAccess) {
error("double use");
}
allowAccess = true;
onAccessAllowedAfter(object);
}
private void denyAccess() {
if (!allowAccess) {
error("double free");
}
onAccessDeniedBefore(object);
allowAccess = false;
denyThrowable = new Throwable();
}
private void checkMethodAccess(String name) {
if (!allowAccess) {
switch (name) {
case "hash":
case "equals":
case "toString":
case "finalize":
break;
default:
error("use after free");
}
}
}
private void error(String message) {
throw new CacheReusableCheckerException(message, denyThrowable);
}
protected void onAccessAllowedAfter(T object) {
}
protected void onAccessDeniedBefore(T object) {
}
}
public interface CacheReusableChecker {
void allowAccess();
void denyAccess();
}
Let's say I have an interface that describes possible request handlers that can service actions requested by a client in the context of some client session state, that is stored by the client:
public interface RequestHandler<State> {
// Perform action in the context of currentState and return updated state
public State request(State currentState, String action);
}
To make it easy to implement the RequestHandlers, I added the generic type State, which encapsulates all the required client session data.
Now, a simple client could look like this:
public class Client {
private final RequestHandler<?> handler;
private Object state;
Client(RequestHandler<?> handler) {
// Initialize the RequestHandler to use for "go"-requests
this.handler = handler;
// Initialize our client state to "null"
this.state = null;
}
public void go() {
// Execute "go"-request in current state and update state
state = handler.request(state, "go"); // <= this is an error (see below)
}
}
During creation it gets provided with a RequestHandler, which it then later uses to execute "go"-requests. It also manages storage of its current session state in the private state variable.
Now, since my clients shouldn't need to worry about what the session state actually looks like internally, I would like to use RequestHandler<?> as shown. But, unfortunately, this gives me an error in the state = handler.request... line:
The method request(capture#3-of ?, String) in the type
RequestHandler is not applicable for the arguments
(Object, String)
Is there an issue with just changing the offending line to:
state = ((RequestHandler<Object>) handler).request(state, "go");
(which turns the error into an "Unchecked cast"-warning)
Clearly, this way I loose type-checking on my state-object, but if the Client only ever sets it to null or something returned by the RequestHandler, there should be no problems, right?
I know I could also just parameterize Client as Client<State> as well and then using State in place of Object and ? everywhere. But I would rather like to avoid this, since it's (in my opinion) just dead weight in this case that will have to be carried around wherever a Client is instantiated or used...
There is no way to cast state to (?), right?
UPDATE:
There's a beautiful solution to this problem if everything was happening inside a single method rather than a class:
public <State> void go(RequestHandler<State> handler) {
State state = null;
state = handler.request(state, "go");
state = handler.request(state, "go again");
state = handler.request(state, "go one more time");
}
This, I can call anywhere without having to always specify what State actually is. But there is no equivalent construct for entire classes (some inferred generic argument) is there?
It seems like it would be okay to make Client generic, reflecting the type of the RequestHandler. But, if you want to hide that inside the client, you can do it like this:
public final class Client
{
private final CaptureHelper<?> helper;
<T> Client(RequestHandler<T> handler) {
this.helper = new CaptureHelper<T>(handler);
}
public void go()
{
helper.request("go");
}
private final class CaptureHelper<T>
{
private final RequestHandler<T> handler;
private T state;
private CaptureHelper(RequestHandler<T> handler) {
this.handler = handler;
}
private void request(String action)
{
state = handler.request(state, action);
}
}
}
Note that this frees anyone using a client from caring about the generic type of its RequestHandler. Users would have code like this:
RequestHandler<?> handler = ... ;
Client client = new Client(handler); /* Look ma, no generics! */
client.go();
It appears that your intention is that clients should be able to define RequestHandlers that consume and return a variety of objects conforming to a State interface. If so, you need to define your interface like this so that the clients can specify the particular State type they're using:
public interface RequestHandler<StateType> {
// Perform action in the context of currentState and return updated state
public StateType request(StateType currentState, String action);
}
If your Client class is intended to be generic (in the non-technical sense), then it should also be generic (in the technical sense) by allowing subclasses or its own clients to specify the type of the State object:
public class Client<StateType> {
private StateType state;
...
}
The problem with your existing code is that there's absolutely no information contained in an absolute wildcard. When the wildcard represents a return type, it might be the case that you're getting an object of class Object, with no useful behavior, and as an argument type, it would basically mean that the client could expect you to supply an object of any specific class but wasn't saying which.
In Java, how do you get the original class object and/or class name of a Java EE (CDI) proxy?
When using getName() on a proxy instance, the name returned is something like
com.company.employeemgmt.EmployeeManager$Proxy$_$$_WeldSubclass
Is there some functionaliy in Java SE (7) or EE (6) that will return either the original, unproxied class instance or its name?
I need:
com.company.employeemgmt.EmployeeManager
Of course, I could simply use string manipulation, but I would like to know if such functionality is already Java-(EE)-inbuilt.
I already found java.reflect.Proxy, which I could use to detect proxies:
public static void doSomething( Class<? implements Serializable> managerClass )
{
if ( Proxy.isProxyClass( managerClass ) )
{
// unproxy how?
managerClass = managerClass.getUnproxiedClass();
}
// delegate
doSomething( managerClass.getName() );
}
public static void doSomething( String prefix )
{
// do real work
...
}
..., but how would you dereference the original class?
Update:
The trick would be to access MyUtil.doSomething( EmployeeManager.class ) (or MyUtil.doSomething( EmployeeManager.class.getName() )), but I would like to use/pass MyUtil.doSomething( this.getClass() ) (or MyUtil.doSomething( this.getClass().getName() )) from all clients as this code can be copied around without manual changes.
Since the proxy class inherits from the original class, I think that you can obtain the original class by getting the proxy superclass.
It depends. You can get the InvocationHandler for a proxy using Proxy.getInvocationHandler(manager). Alas, InvocationHandler is an interface with only one invoke method and with no feature that lets you get a target class; it all depends on the implementation.
As an example the CXF web servcie framework has a Client and uses a ClientProxy as an associated invocation handler, you can get the Client as such:
ClientProxy handler = (ClientProxy)Proxy.getInvocationHandler(proxiedObject);
Client client = handler.getClient();
To add insult to injury, it seems that the WeldInvocationHandler that you are probably using simply delegates the call to a org.jboss.wsf.spi.invocation.InvocationHandler that that it stores its delegate in a private field. So you need to do quite some magic with reflection to find out the actual class of the target object.
Since proxy implements interfaces it proxies, you can use Class<?>[] Class.getInterfaces()
to find out proxied class(es).
private Class<?> findProxiedClass(Object proxiedObject) {
Class<?> proxiedClass = proxiedObject.getClass();
if (proxiedObject instanceof Proxy) {
Class<?>[] ifaces = proxiedClass.getInterfaces();
if (ifaces.length == 1) {
proxiedClass = ifaces[0];
} else {
// We need some selection strategy here
// or return all of them
proxiedClass = ifaces[ifaces.length - 1];
}
}
return proxiedClass;
}
Test it with
#Test
public void testProxies() {
InvocationHandler handler = new InvocationHandler() {
#Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
return null;
}
};
RandomAccess proxiedIface = (RandomAccess) Proxy.newProxyInstance(
RandomAccess.class.getClassLoader(),
new Class[] { RandomAccess.class },
handler);
Assert.assertEquals(RandomAccess.class, findProxiedClass(proxiedIface));
Assert.assertEquals(Object.class, findProxiedClass(new Object()));
}
I am new to writing API's and did some research and realize to accomplish what I want I would need to do it using Dependency Injection. I am writing an android application that haves two data source. One is expose by web services and the other is SQLlite. The SQLlite is used as backup when no data connection is available (Only interested for the webservice portion of the API for the time being will refactor). I want to write a API that provides a layer of abstraction to this that calls the right data access class based on the model required. Therefore, I have a interface that describes methods that the api should implement, called IDataAccess (Only interested in getAll for the purpose of figuring out what to do).
public interface IDataAccess {
public <T> List <T> getAll ();
public <T> T getById (int id);
}//end IDataAccess
I am using Guice for dependency injection. The guice module is:
public class Data extends AbstractModule {
public void configure () {
bind (IDataAccess.class).to(UserData.class);
}
}
and a Implementation of IDataAccess is (Note I am using Jersey Client API):
public class UserData extends DataAccessManager implements IDataAccess {
#SuppressWarnings("unchecked")
public List <User> getAll () {
WebResource webResource = client.resource (WebResourceURL.URL_USER_ALL);
ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (response.getStatus () == 200)
return response.getEntity(new GenericType <List <User>> () {}) ;
else
return null;
}//end getAllUsers method
}
I have a class that loads and instantiates any resource needed. It also returns a instance of a DataManager called DataAccessFactory.
public class DataAccessFactory {
private Client client;
private static DataAccessFactory instance;
private DataAccessFactory() {
client = Client.create();
}
public static DataAccessFactory getInstance() {
/*
* check if instance variable is instantiated.
* if it is not then instantiated it and returns
* created instance.
*/
if (instance == null) {
instance = new DataAccessFactory();
return instance;
} else
return instance;
}//end getInstance method
public DataAccessManager createDataAccessManager() {
return new DataAccessManager(client);
}//end createDataAccessManager method
}
Then I have the actual DataAccessManager class:
public class DataAccessManager {
protected Client client;
protected DataAccessManager (Client client)n{
this.client = client;
}//end constructor
public <T> List <Object> getAll(T t) {
Data module = new Data ();
Injector injector = Guice.createInjector(module);
IDataAccess data = (IDataAccess) injector.getInstance(t.getClass());
return (List<Object>) data;
}//end fetchAllUser method
}
To call the user model on this class I would do something like this:
#Test
public void fetchUser () {
DataAccessManager m = DataAccessFactory.getInstance().createDataAccessManager();
List<User> user = (List<User>) m.getAll(new Userdata ());
if (user == null)
assertEquals(1, 2);
else
assertEquals(1, 1);
}
Ideally what I want this to do now is, call the UserData to get all the User objects or the OrderData (When implementation is written) class to get all the order objects etc.
The problem is that this is giving a error:
Cannot cast from List to List
.How can I fix this problem or restructure this so that it makes sense?
1) You are creating an injector (Guice.createInjector) per request. Injector creation is expensive and should normally be done during application loading. You should see DI as a bootstrap mechanism and keep it simple.
2) You don't need the DataAccessFactory. First there is no need for a factory as the createDataAccessManager instantiation does not require any logic and secondly Guice could also take care of the factory pattern.
I would personally keep it simple and inject with Guice directly the UserData instance into each service that needs it, without using the rather complicated Abstraction approach showed here. Still, it does not solve the problem of dealing with network issues. My guess is that each data access class will have to deal with connectivity in a specific way, so the logic should be directly here.
For the list casting problem, see http://docs.oracle.com/javase/tutorial/java/generics/subtyping.html
If you will continue that way, I would recommend to read about erasure also.
It's a common problem you fall for. We'd expect that as String is-a Object, List<String> is-a List<Object> is true too. But it isn't. This is why this class cast won't work:
#Test
public void fetchUser () {
//...
List<User> user = (List<User>) m.getAll(new Userdata ());
//..
}
I suggest to rewrite the DataAccessManager.getAll() method to return the right kind of list.
For the record, I found a typo in DataAccessManager.getAll() method. I think when you wrote return (List<Object>) data; then you rather wanted to write return List<Object> data.getAll(); Otherwise you just cannot cast IDataAccess to List.
To escape from this casting hell I suggest to add a type to the IDataAccess interface and to its implementations:
public interface IDataAccess<T> {
public List <T> getAll ();
public T getById (int id);
}//end IDataAccess
public class UserData extends DataAccessManager<User> implements IDataAccess<User> {
// your implementation
}
I'd also clarify DataAccesManager itself:
public class DataAccessManager<T> {
//fields and constructors
public List<T> getAll(IDataAccess<T> access) { //this is how the test suggests you want to use this method
Data module = new Data ();
Injector injector = Guice.createInjector(module);
IDataAccess<T> data = (IDataAccess<T>) injector.getInstance(access.getClass()); //why is this line important? why don't you use the access parameter instead?
return data.getAll();
}
}