How do I extend Java classes by Reflection? - java

I have two Strings:
String a="org.test.A";
String b="org.test.B";
I get a class by Reflection
Class aClass = Class.forName(a);
I want aClass extends b, like:
Class okClass=aClass.extends(b);//how to implement this?
how to implement this?
how to get okClass?
thanks!

Apart from using a JDK dynamic proxy, which works only by interface, you can use CGLIB or javassist for extending classes at runtime.

Generally speaking you want to be able to create new classes (not objects) at runtime. You can use bytecode engineering or java compiler api for that.

You could start by reading up on dynamic proxies. Proxies do not extend classes, but they do implement interfaces which you can map on your class implementation through the invocation handler.

As said before I'd recommend to look at CGLIB but there is also javassist which is a class library for editing bytecodes...

Related

correct way to instantiate bunch of classes at once

I have a class Main.java in which I need to instantiate a bunch of other classes say C1.java ... C50.java. I am not able to think of an elegant way to instantiate these 50 classes in Main class. If I simply put all instantiating code in one place it looks so crowded and ugly. Today I have 50 classes to instantiate, tomorrow this count can increase to 100, then this situation will get worse. Can you please suggest an elegant way of instantiating all these classes without making Main class crowded with instantiation code. I am not aware of any design pattern to do this.
I am thinking to create an array of classes that needs to be instantiated and use reflection to instantiate them.
The answer depends on what purpose the classes would serve. However, if you don't mind to end up with an unordered collection of instantiated classes, there is a way to go using Reflections library and I guess also a shorted one in the matter of lines of code:
// find out all the classes implementing MyInterface
Set<Class<? extends MyInterface>> subTypes = reflections.getSubTypesOf(MyInterface.class);
// iterate those classes and instntinate them
List<MyInterface> objects = new ArrayList<>();
for (Class<? extends MyInterface> clazz: subtypes) {
objects.add(clazz.newInstance());
}
In any case, the whole design should be rethough.
The recommended solution is to use the service loader architecture.
Instantiating all registered implementations of MyInterface can be done as simple as
for(MyInterface my: ServiceLoader.load(MyInterface.class)) {
/* do something with <my> */
}
To make this work, its not enough to just implement the interface, these implementations must be declared as service providers, either via an entry in META-INF/services/ of your jar file (as described in the linked class documentation) or via provides declaration within a Java module declaration when using Java 9 or newer.
The advantage of this is not only a higher performance, compared to searching the entire class path with a reflection library, it also ensures that the necessary access rights are established when using Java’s module system in the future.
See also Java 9’s version of the class documentation.

Identify annotation class in java

I have a utility that scans different classes in the classpath, and checks for unused classes.
Some classes need special treatment, like interfaces and abstract classes. Those can be easily identified using reflection.
The problem arises when trying to identify a class that is an annotation class (i.e. #interface).
Is it possible to know if a class is really an annotation?
Yeah.. It's possible to know if a class is really an annotation.
Please try this:
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Class.html#isAnnotation%28%29
http://java.dzone.com/articles/discovering-java-annotations
It may help you

Why does a CustomFieldSerializer need static methods?

You use a CustomFieldSerializer to define custom serialisation and deserialisation for an object.
It's ostensibly easy to define custom serialization for your class Xxx:
create a class called Xxx_CustomFieldSerializer that extends CustomFieldSerializer<Xxx>,
implement abstract methods serializeInstance and deserializeInstance, and optionally instantiateInstance.
This generates a gazillion compile errors that boil down to the following:
subtype Custom Field Serializer 'Xxx_CustomFieldSerializer' does not define a deserialize method: 'public static void deserialize(SerializationStreamReader reader,Xxx instance)' (reached via Xxx)'
It wants you to create static methods that do exactly what the implemented methods do. Obviously one delegates to the other, but it means you can't extract out all of this boilerplate for similar types Xxx.
Why? Is this just left over from an old version of GWT or something? Is there a way to avoid having to write all the extra stuff?
Thanks to Thomas Broyer for finding this. It's just a limitation in GWT.
See: com.google.gwt.user.rebind.rpc.CustomFieldSerializerValidator
See: http://code.google.com/p/google-web-toolkit/issues/detail?id=7331&thanks=7331&ts=1335182609

Does 'extends Object' have a purpose or is it redundant?

Following a tutorial on the internet regarding Soap development with Java, I found this link, with a rather unusual code for myself.
The code:
public class SoapService extends Object {
/** Creates new SoapService */
public SoapService() {
}
/** This is the SOAP exposes method
*/
public String sayGreeting(String name)
{
return "Hello "+name;
}
}
What's with the 'extends Object' syntax ? I've never encountered this kind of syntax (only on Generics).
Does this syntax has any purpose or is 'plain dumb' ?
Unless the Object class is not actually the java.lang.Object class (the tutorial does not include the imports, so it's hard to see), the extends Object is redundant.
All objects in Java implicitly extend Object, so I'd say it's redundant.
All classes extend Object implicitly anyway so it's just redundant coding having no impact.
Looks a bit like generated code - it's extra effort for a source code generator to omit the "extends" clause if it is not needed, especially if the generator is template-based.
It just means it inherits directly from the Object class. Here is more about inheritance in Java.
No. It's just explicitly doing something that is implicit.
It's unneeded. Every class in Java extends Object at some level. Leave it out, unless you need to clarify something specific.
Extends clause is optional as stated in Java Language Specification. If it is omitted, the class is derived from java.lang.Object. It is just a matter of coding style to write it or not to write it in this case. Usually it is omitted.
It is silly code. Every class in Java extends an Object class. No need to type this explisitly
There is one possibility and that is the person who made it don't want you to extend any classes. You can always do a workaround of course but that is the only thing I can come up with that makes sense.
I think it's redundant.
In Junit source code:
public class TestFailure extends Object {}
I don't know why this class extends Object.
My vote, plain dumb - but then I only play with Java...
But any class inherits from the Object Class as far as I know...
It is legal but useless boilerplate. Everything extends Object so the language spec allows you to leave it out, and it generally should be left out (some writers of coding standards disagree).
The situation is the same in generics (extends Object is implicit and redundant), it is just that for some reason (I have seen some claim early buggy Generics implementations had issues with the ? wildcard) it has caught on a bit more there.
As a matter of fact, it does not seem to be simply redundant, especially when working in the JWS webservices environment.
When defining a class for an XML type to be transported over SOAP, I use the wsimport tool to fetch client dependencies from the WSDL, which creates package-local copies of these classes. By explicitly extending Object, one can seamlessly cast between the classes from the two distinct packages.
Not doing so leads to a compilation error when trying to use a class method from package A that expects an argument type of the class in in package A, and passing in an object generated from the equivalent class in package B.
As java is an object oriented language, it supports inheritance which inherits the properties of the another class, for example all java objects inherits from java.lang.Object class.From the above example it is understood that it is the explanation of inheritance. Note that all classes, whether they state so or not, will be inherit from java.lang.Object.
Any class that doesn't explicitly extend another class,implicitly extends Object
all classes extends the java.lang.Object by default. You can see it
here
Why not make it explicit?
I'm for adding it in - not everyone "implicitly" knows that every Java class implicitly extends Object. By writing it explicitly they don't have to guess.

How to create an interface at Runtime

Assuming I have a class like
public class FooImpl
{
public void bar(){};
}
Is there a way to create its interface at runtime?
e.g.
public interface Foo
{
public void bar();
}
I have been looking into Javasssist and the truth is it's reflection that I'm interested in using the interface for (as Esko Luontola and Yishai stated)
So I want an interface that specifies a subset of the original class' methods to make a proxy from.
I came to realize there are more things to be concerned about like
Should you reuse that interface or create a new one each time?
The proxy class is effectively a new instance of type java.lang.reflect.Proxy, which might cause implications depending on the use case.
The last point made me wonder on how some frameworks manage to handle this, do they deep copy the object? do they encapsulate the proxy inside the original instance?
So maybe it's just easier (though maybe not as elegant) to require for the client code to create the interface for the class.
You can do it with some bytecode manipulation/generation during class loading, for example using ASM, Javassist or similar, maybe also AspectJ.
The important question is, why would you need to do that? No normal code can use the class through its interface, because the interface does not exist at compile time. You would either need to generate the code that uses the interface or use reflection - but in that case you might as well use the original class. And for the interface to be useful, you should probably also modify the original class so that it implements the generated interface (this can be done with the libraries I mentioned).
You can look at something like Javassist to create the class. You would go over the class with Class.getMethods() and have to implement the bytecode at runtime for the interface, and then use the Proxy class to bridge the interface and implementation.

Categories

Resources