Java extend class with a reflected class - java

I tried to make a reflection to my code but I came across a problem because I had to extend class with reflected class, it was something like this:
I have this classes reflected:
"some.package.a.SomeClass"
"some.package.b.SomeClass"
and now I need to extend another class with one of them
public MyClass extends SomeClass {
#Override
public Object...
is there any way that I can achieve this?

Using off-the-shelf Java, you cannot extend a class given to you only through reflection. There are third-party libraries that let you overcome this restriction (see this Q&A).
Extending a class requires defining a new class, and compiling it into bytecode. Reflection happens at run-time. It is inherently a read-only API, so you cannot emit new classes with it.
Implementing an interface gives you another option of using a Proxy, but you cannot specify your own base class.

Related

Is it useful to have an abstract class without Abstract methods? [duplicate]

I am now studying a java and I'm at the part of Abstract.
I read sorta strange part to me that there is an abstract class
which does not include any abstarct method.
Why do they use this kind of class?
To prevent instantiation of that class and use it only as a base class. Child classes can use the general methods defined in the abstract class.
For example it doesn't make sense to create an instance of AbstractVehicle. But All vehicles can reuse a common registerMileage(int) method.
A common reason to do this is to have the abstract class provide exploding implementations of the abstract methods as a convenience to subclasses who don't have to implement all the abstract methods, just those they want to - the remaining ones will still explode but it won't matter if those execution paths aren't exercised.
HttpServlet is an example of this pattern in action. It has default implementations for all methods that handle the different request types, but they all throw an exception. The subclass must override these if they want to do something meaningful. It's OK to leave some handler methods not overridden as long as they are never called.
Yes, we can have abstract class without any abstract method.
Best example of abstract class without any abstract method is HttpServlet
If this class extends another abstract class and don't have implementation of inherited abstract methods.
This class contains some common logic for all its inheritors, but itself does not represent usable entity (in terms of particular application)
These type of classes are used for a implement a general logic which can be implemented by other classes. Making it abstract prevents from instantiating it. But other classes can inherit the class and its methods.
Say you have a set of related classes, but no related (shared) code, yet. If we make all of these classes extend a base class with no abstract methods, that then if we wan't all of these classes to have an identical method/feature in the future, that can be done in one shot by putting it in the base class. So code is not repeated and it reflects in all child classes by including it in just one place.
Another example for having such class is when you implement creation helpers. These classes are used to ease the client in the creation of objects, which are related in topic but decoupled depending on the need. By nature, the methods of this creator classes are all static and they can be seen as utility classes as well.Obviously, instatntation of this classes is futile and hence the abstractkeyword.
To mention a recent example I met was the Sftpclass from org.springframework.integration.dsl.sftp which is basically an easy way to require objects (e.g: adapters, gateways) from the sftp api.
I develop a abstract class to prevent instantiation of that class and use it only as a base class. because, These type of classes are used for a implement a general logic which can be implemented by other classes. Sometimes, I have a default implementation for every method in abstract class. In the manner, it doesn't force the sub-class to override all of method, but also it implement everyone that is need.It means implicitly you have to override at least one method to make scene using this abstract class.
I can't think of any good reason to use it. It could be used as "marker" but an interface would be a better choice.
Abstract class without abstract method means you can create object of that abstract class.
See my Example.
abstract class Example{
void display(){
System.out.println("Hi I am Abstract Class.");
}
}
class ExampleDemo
{
public static void main(String[] args)
{
Example ob = new Example(){};
ob.display();
}
}
If you write one abstract method inside abstract class then it will not compile.
Which means if you create abstract class without abstract method then you can create Object of that Abstract Class.

Object vs Extend in Java

I may be wrong as I have not got too much experience with Java, but here is a question.
I have a class which contains many methods (basically it is a simple library).
I create an object of this class let's say MyLibrary obj = new MyLibrary(parameters);
The parameters set up any necessary functionality for the library to run correctly.
Then I can call obj.getSomething/obj.setSomething/obj.createSomething etc etc...
In my main class I really need only one this kind of library object.
Now... Would it be more useful for me not to use it as an object, but put it as extends and then create a function inside of the library like a constructor which I would call manually?
EDIT:
The relation between the one class and MyLibrary is very close. Basically, I have many classes which do similar things but have some different higher layer functionality. So I separated method which must be in all those classes.
It seems it is very similar to shape class and triangle, circle, square example. So MyLibrary is similar to shape which contains all the foundation.
What you described strongly resembles a utility class, similar to Java's Collections. The class has only static methods, and a private constructor to prevent instantiations. This is a well-known idiomatic pattern in Java - you can use it to create your own groups of methods providing related functionality.
You should not extend, or even instantiate, utility classes at all. Starting with Java-5, you can statically import them so that you could use their methods without making an explicit reference to their class.
extends is used when you need an inheritance hierarchy. It seems more logical to put your code in two separate classes here, like you have it now.
Also, if your "library class" does multiple unrelated things, it should probably be split into multiple classes - one for each task.
You should really only use extends when you have a is-a relationship. So, you can think, is my main class a MyLibrary or should my class have a MyLibrary.
From your described problem, it sounds like having MyLibrary is the way to go.
With the limited detail that you have provided, you might want to consider the Singleton pattern.
extends should only be used when one object needs to inherit the characteristics and functionality of another one because they are very closely related. For example, if you have a Shape class, then you would extend Shape to create Circle, Square, and Triangle. Before you use extends you should learn more about inheritence and when you should and should not use it.
I would make this a static class to use. Similiar to javas MATH class API for math class. You can just use the methods of the class without making an object of it.
Well If your class if performing utility functions then you should mark all methods as static and use operations like
MyLibrary.doSomething();
MyLibrary.createSomething();
MyLibrary.getSomething();
But this wont allow you to keep some data members in the class and if you keep them they will be static as well.
I don't think so that extends suits your case.
Also if you want to keep only an object then you should look at Singleton A class for which only one instance can be created.
Assuming you are just using MyLibrary and may not alter it, you should use a wrapper that makes the whole thing a Singleton, as already proposed by Code-Guru.
public class MyLibraryWrapper {
private static MyLibrary instance = null;
private MyLibraryWrapper() {}
public static MyLibrary getInstance() {
if (instance == null)
instance = new MyLibrary();
return instance;
So in your code you would use
MyLibraryWrapper.getInstance().getSomething();
Best way to create singleton in java 1.5 or above is to use ENUM.
public enum Test {
INSTANCE;
}
INSTANCE is the only instance of Test class.

public class Extra<BASE> extends BASE

Is there a way to inherit from a baseclass by using the generic type paramater?
public class Extra<BASE> extends BASE
So that Extra is the new class having all the methods of BASE, like
Extra<MyType>
Greetings
edit*******
That is disappointing. I'm moving a project from C++ to JAVA.
In C++ this is possible, sadly I used this a lot in this project.
Is there another way to achieve that:
A class has its own userdata-class. It needs the members of its userdata linked with a special functionality, that is given by an other class. The other class is extending the first userdata-class. I don't want to have the userdata as a data member in the new class,
but really as a part of it.
Like:
userdata-class:
String name;
special-functionality-class: a generic TreeKnot,
The new class then should be a TreeKnot combined with the userdata-class.
What way could I go ?
No, it is not possible you can create something like this
public class Extra extends Base<Base>
But what do you want it is not possible at all!!!!
No, it's not possible. Type templating and inheritance are two completely different concepts.

How to make an abstract class non-abstract with Javassist?

In a small framework I am building, I would like to change certain abstract classes to non-abstract using Javassist.
I already transformed all the abstract methods in non-abstract ones implementing the dynamically generated code I need. But I have not yet succeed in making the class non-abstract.
What I have tried is something similar to this:
Let's say c is the class I would like to make non abstract. So I have written:
public void instrument(Class c) {
...//some ignored exception management
CtClass ctClass = ClassPool.getDefault().get(c.getName());
ctClass.setModifiers(c.getModifiers() & ~Modifier.ABSTRACT);
return ctClass.toClass().newInstance();
}
However, the call to:
ctClass.toClass();
is raising the following CannotCompileException:
"attempted duplicate class definition for name: <class_name>."
This is because the class has already been loaded, since I am invoking its getName method. It seems to me this is the only mechanism I have to get a CtClass from an existing class, but please someone tell me if that is not correct. Hardcoding the name of the class instead of calling its getName method is far from been an ideal solution, given that I need to apply this routine to many classes.
Any workaround to do this ?. If it is not possible at all I will dynamically generate a new class that extends the abstract class, implements its constructors, and the abstract method of all its ancestors (a bit more complicated, so I would be very happy if I succeed just making the original class non-abstrat instead).
Have you tried creating an extending Class rather than changing the existing Class? So create a Class, implement all the methods and use setSuperClass() to make it extend your abstract Class.
The problem, as you described it, is that you have already loaded the Class you are attempting to redefine. It is illegal to attempt to redefine a class that is already loaded by a classloader.
One option might be to do a bit of classloader trickery: create a new classloader that doesn't have your existing classes loaded (parent is the system classloader) and have Javassist load through that (use aCtClass.toClass() method that takes a ClassLoader argument).
As it has suggested, there might be a better way to achieve your goal, and creating subclasses might be a better design. Is using interfaces instead of abstract classes an option? If so, dynamic proxies is an option as well, their advantage being you don't need any 3rd party libraries to create them.

Java: extending Object class

I'm writing (well, completing) an "extension" of Java which will help role programming.
I translate my code to Java code with javacc. My compilers add to every declared class some code. Here's an example to be clearer:
MyClass extends String implements ObjectWithRoles { //implements... is added
/*Added by me */
public setRole(...){...}
public ...
/*Ends of stuff added*/
...//myClass stuff
}
It adds Implements.. and the necessary methods to EVERY SINGLE CLASS you declare. Quite rough, isnt'it?
It will be better if I write my methods in one class and all class extends that.. but.. if class already extends another class (just like the example)?
I don't want to create a sort of wrapper that manage roles because i don't want that the programmer has to know much more than Java, few new reserved words and their use.
My idea was to extends java.lang.Object.. but you can't. (right?)
Other ideas?
I'm new here, but I follow this site so thank you for reading and all the answers you give! (I apologize for english, I'm italian)
If it is only like a "research" project in which you want to explore how such extension would work, you could provide your own implementation of the Object class. Simply copy the existing object implementation, add your setRole method etc, and give -Xbootclasspath:.:/usr/lib/jvm/java-6-sun/jre/lib/rt.jar as parameter to the java command. (I will look for api-classes in . before looking in the real rt.jar.)
You should consider using composition rather than inheritence to solve this problem; that way you can provide the functionality you need without using up your "one-shot" at inheritence.
For example, the JDK provides a class PropertyChangeSupport, which can be used to manage PropertyChangeListeners and the firing of PropertyChangeEvents. In situations where you wish to write a class that fires PropertyChangeEvents you could embed a PropertyChangeSupport instance variable and delegate all method calls to that. This avoids the need for inheritence and means you can supplement an existing class hierarchy with new functionality.
public class MyClass extends MySuperClass {
private final PropertyChangeSupport support;
public MyClass() {
this.support = new PropertyChangeSupport(this);
}
public void addPropertyChangeListener(PropertyChangeListener l) {
support.addPropertyChangeListener(l);
}
protected void firePropertyChangeEvent() {
PropertyChangeEvent evt = new ...
support.firePropertyChangeEvent(evt);
}
}
you can extend Object - every class extends it.
you seem to need something like multiple inheritance - there isn't such a thing in Java
if you want to add functionality, use object composition. I.e.,
YourClass extends Whatever implements ObjectWithRoles {
private RoleHandler roleHandler;
public RoleHandler getRoleHandler() {..} // defined by the interface
}
And then all of the methods are placed in the RoleHandler
If you're talking about adding a role to all your objects I would also consider an annotation-based solution. You'd annotate your classes with something like #Role("User"). In another class you can extract that role value and use it.
I think it would need an annotation with runtime retention and you can check, run-time, whether the annotation is present using reflection and get that annotation using getAnnotation. I feel that this would be a lot cleaner than extending all your classes automatically.
I believe there are some frameworks which use exactly such a solution, so there should be example code somewhere.
If you are doing what you are doing, then inheritance is probably not the correct idiom. You may want to consider the decorator pattern, whereby you construct a class that takes as its parameter some other class with less functionality, and adds some additional functionality to it, delegating to the existing class for functionality that already exists. If the implementation is common to many of your decorators, you may want to consider putting that functionality in class that can be shared and to which you can delegate for all your decorators. Depending on what you need, double-dispatch or reflection may be appropriate in order to make similar but not quite the same decorators for a large variety of classes.
Also, as has been pointed out in the comments, String is declared "final" and, therefore, cannot be extended. So, you should really consider a solution whereby you delegate/decorate objects. For example, you might have some object that wraps a string and provides access to the string via getString() or toString(), but then adds the additional functionality on top of the String class.
If you just want to associate some objects with additional attributes, use a Map (e.g. HashMap).
What you really want to do would be monkey patching, i.e. changing the behaviour of existing classes without modifying their code.
Unfortunately, Java does not support this, nor things like mixins that might be used alternatively. So unless you're willing to switch to a more dynamic language like Groovy, you'll have to live with less elegant solutions like composition.

Categories