How to add objects to a class that I cannot edit - java

I am using the StdDraw.java library and I can't edit the file. I want to add various items to the JFrame such as JMenu, buttons and others without compromising the canvas and the Jframe.
I have tried something like
StdDraw.class.getMethods"
Yet I can't seem to get it to work. It seems I can only use the methods inside the class and don't add some of my own or edit the ones already in.
The file is available online. How would I be able to achieve the above?

StdDraw.java is a final class, if I am not mistaken. A final class cannot be extended. So you have two options:
You can directly use source then add your own attributes and compile it yourself, if the license permits this kind of usage.
You can encapsulate StdDraw.java class, with your own wrapper class and direct method calls using Java Reflection.

Use inheritance.
class MyClass extends JFrame {
String myField = ""; //--- This is my own field!
}

Related

importing a library as a package private

I know we can create a package private class in java. So the class is Internal and only accessible in the specified module:
class MyPackagePrivateClass
{
...
}
Now I am developing an android library which i named LibraryA and I wish to use an existing LibraryB in my own LibraryA. How is it possible to prevent user of LibraryA from using the LibraryB directly?
Is there any concept like package private library or anything like that?
Update (For those who ask 'why do I need this?')
In LibraryB there are methods like this:
public QueryBuilder select(String... columns);
But I strongly am of the view that we should use Type-Safe Enum pattern and prevent users from passing strings to these methods(Considering maintenance and refactoring issues). So I decided to wrap those methods in LibraryA:
public TypedQueryBuilder select(Column... columns) {
queryBuilder = queryBuilder.select(toString(columns));
return this;
}
Therefore users of my library should use the Typed methods I provided (Column is a type safe enum here). But if they have access to the original method they may use those instead and I tend to forbid this.
In Java, with polymorphism, you can't hide a public method of an extended class.
I think that you could archive your goal with Facade Pattern: hide all the complex logic and, in this case, control the access and, if needed, implements some interfaces.
Jigsaw project tries to reach the same goal. But it can take long enough to wait until it would be ported to Android. Until then the best solution IMO is to use package private methods. User will be able to understand that he shouldn't use these methods.
Anyway it's impossible to ultimately forbid library user to do certain things, because one can use reflection or substitute class to get rid of nasty restrictions. But it's possible to encourage user not to do certain things - that's what can be done.
Make a jar file out of library B and import it in library A.
https://stackoverflow.com/a/1051705/6897626

Should I use an extra class or style the instance?

I'm using a UI framework which doesn't follow a strict MVC design. I create a component and add the appropriated properties to "style" this instance of a class. Some pseudo code:
Button bu = new Button();
bu.setCaption("Something");
bu.addClickListener(...);
bu.setAnotherProperty(1);
However, when do I decide to make an extra class instead of this whole setter block?
Like (pseudo code):
public class MyButton extends Button {
this.setCaption("Something");
this.addClickListener(...);
this.setAnotherProperty(1);
}
Is it a good practice to do it like this always? Is it a bad practice to do it in general? Or is there a special case where one should decide to create a class instead of a huge setter block?
Your MyButton isn't really (at least based on the code shown) a special type of button. It's just a Button with some parameters set in a certain way. Based on that I would probably not create a separate class, but factory methods that build buttons according to different specifications.
This has the added benefit that if you suddenly realize that you need 2 types of "special" buttons, you'd add another factory method instead of creating another class that's still basically just a Button with some extra make-up.
So instead of Button b = new MyButton(); I'd have something along the lines of (implementation style free) Button b = ButtonFactory.myButton();.
Do you use your custom button more than once? If so, then it would be good practice to create a separate class. If not, then generally it is not necessary.
Even if this custom button is only used once, I'd still recommend a separate class for "safe keeping".

coding structure in netbeans

This is a question from newbie in both Java and Netbeans. I have searched a lot in google before posting it here.
I am using netbeans to create a gui application. In the standard books, the structure for java coding is suggested as,
class className{
field names
constructor(){
}
method1(){
}
method2(){
}
main method(){
}
}
In Netbeans,
class ClassName{
constructor(){
initComponents();
}
initComponents(){
}
//autogenerated code for methods related to swing actions
action1(){
}
action2(){
}
main method(){
}
field Names;
}
My question is, where do i write method1() and method2()? Should i have to put the fieldnames at the end or on top? - the autogenerated fieldnames cannot be edited. So, should i have to write the field names which i declare on top or at the bottom. I know that anywhere will work. But i want to make sure i am coding them at the right place. Thanks
Some if this is personal preference. Some people like the fields at the end of the class, I personal like them at the start.
I tend to put the constructor first, followed by the methods and allow the auto generated code to sit towards the bottom and I put inner classes at the end.
But that's just me.
I'm not sure how Netbeans works, but if it generates code in your file, perhaps you should store your own functions somewhere else, this way you can freely choose your structure without having Netbeans taking up a section of your file.
In fact, you can write your methods wherever you think the best place is.
For Swing app, Netbeans will use this rather awkward class structure you've just showed - with the instances variables, constants and the like at the bottom of the class.
Personally I prefer to put the constants at the top, followed by variables, constructors, public, protected, default and private methods (in this order) - then any inner class (if there is any).
There must be a way to change Netbeans class template - but I've never digged into the templates setup of Netbeans for the classes structure - only for the header's comment.

Overriding User Library Classes in Java

I code java with BlueJ for Mac. I have added the stdlib.jar library (From princeton http://introcs.cs.princeton.edu/java/stdlib/). Before added this library I had my own class named StdDraw.java (The specific class I was using on the project) and copy/pasted the code. I also adjusted some of the code and added some new lines. Since I cannot edit the libraries code, how may I override or extend library classes to add additional functionality?
Since the library classes are final, you can't extend them. Another option is to wrap them in your own classes. For example, you can create your own drawing class that has an instance of StdDraw that it delegates to. For many of your methods you can call the corresponding method of the StdDraw instance, or you can simulate overriding by implementing methods yourself.
Just simply extend the class,
public MyClass extends ClassFromLib
make sure the library jar file is on the classpath. If the author of that class declared it as final indicating that it's not suitable for subclassing. then the best alternative is to use the delegate pattern.
I wrote the code below in this editor so no promises that it complies, but hopefully you get the idea.
public Myclass {
private ClassFromLib cfl = new ClassFromLib();
public void methodA(){
//Do whatever you need here
cfl.methodA(); //Doesn't have to be the same name.
//Do whatever you need here
}
}

Make a class extends another class at runtime

There is a library have a base class (let's call it CBase) that performs some tasks and one can create classes that extends this CBase class.
The behavior of the CBase is not enough for me, so I would like to create my own CBase class (let's call it MyCBase) that have the same methods and members but these methods don't do the same thing.
Until now everything is ok. But what blocks me is that I would like to replace CBase by MyCBase. However, I have a lot of classes that extend CBase and I don't want to change them all.
Is it possible to replace CBase by MyCBase at runtime ?
So that
public class A extends CBase {}
becomes
public class A extends MyCBase {}
Can I perform this using code enhancement ? (like we do to add methods to a class at runtime. Is it also possible to change inheritance this way ?)
Thank you for your help !
EDIT
I would like to write a plugin for a framework, this is why I would like to change inheritance at runtime. This way users of the framework can use my plugin without changing their source code (changing the inheritance of their classes from CBase to MyCBase)
EDIT 2
Is it possible to do like this: ?
CtClass cc = CtClass.forName("pkg.AClass");
cc.setSuperclass(CtClass.forName("mylib.MyCBase"));
cc.compile();
I'm not expert. Probably you could extend ClassLoader. But I highly recommend don't do it. The replacement will touch many of your classes but it will be clear in code reading and app execution.
I think there is also room for architecture improvement since you have so many classes extend CBase. People are trying to remove dependencies from other libraries or keep it really small. Because in this case you could easily switch to another library or add your own functionality.
I dont think you can change the extends of a class at runtime. I would suggest to change the extends of the objects or build an interface, which contains all the things your need
Changing all derived classes is a simple matter, provided you control their source code:
Create a new class in your project. Call it CBase, and put it in the same package as the library class.
Use the rename/move refactoring of your IDE to rename CBase to MyBase. This will have the IDE rename all references to the renamed/moved class ...
Write the code for MyBase, extending from CBase.
If you can not do this (for instance because some derived classes are in a library you do not control), you replace the implementation of CBase with your own. Simply create a class of the same package and name in your project (the classloader searches the classpath in order, and uses the first class of the proper package and name it finds). This approach however is very brittle, as the compiler can not check binary compability between the old and new version of CBase. The JVM will check this compatibility when classes are loaded, but since classes are only loaded when needed, its hard to test your changes. (Which is why I do not recommend this approach if there are other options).
You could also change the classes as they are loaded my manipulating the class file, that that's going to be even more brittle, and the compiler would allow you to use any additional features MyBase might have. ==> Definitely not a good idea.

Categories

Resources