Modifying an existing class with GWT generator - java

I have a class (for example District) that implements two Methods:
public Object getAtribute(String name) {
}
public void setAtribute(String name, Object value){
}
Everything is setup to call my Generator when GWT.create(Dirstrict.class) is called.
Now How can I modify the implementation of these methods in the same class(i.e write code inside them) so that the final code in District class will be like this:
public Object getAtribute(String name) {
//The generated code
}
public void setAtribute(String name, Object value){
//The generated code
}
Thanks,

Your generator won't be rewriting the implementation of the District class, it will be generating a subclass of District with a different implementation. That generated subclass is what will be returned by GWT.create(District.class).
Once your generated subclass is written, it will be compiled down to JavaScript and your original superclass implementation may be completely stripped out if it's never used, so the effect will be the same.

You have to create a generator class that extends com.google.gwt.core.ext.Generator and tell the gwt compiler to use your generator to generate the District class.
your.gwt.xml
<generate-with class="my.package.DistrictGenerator">
<when-type-assignable
class="my.package.District"/>
</generate-with>
But first you should think about if you really need to use a generator because it makes the code more complicated.

Related

How do I strictly implement the given UML using Java?

I am trying to implement the UML below using Java:
I have successfully implemented every instruction except one which is:
Theater class:
Override the showArea method and display the size multiply by 12.
I am new to UML and from my understanding, I am not allowed to create constructors in any of the classes. This is confusing since I don't know where I can define the size for showArea.
Below is the working code I have right now.
Place Class
public abstract class Place {
private String placeName;
private int capacity;
private String placeDescription;
private int workingHours;
public abstract void showEvents();
}
Building Class
public abstract class Building extends Place{
public abstract void showArea();
}
Theater Class
public class Theater extends Building{
#Override
public void showArea() {
System.out.println("Theater area : " );
}
#Override
public void showEvents() {
System.out.println("Events ready to be hosted !!");
}
}
Main class
public class CodingtonDemo {
public static void main(String[] args) {
Theater theater = new Theater();
theater.showArea();
theater.showEvents();
}
}
Expected result in console:
Theater area : 6000
Events ready to be hosted !!
My result so far:
Theater area : [No value yet]
Events ready to be hosted !!
The problem with your diagram
Your diagram is a partial representation of your model:
The Place's properties placeName, placeDescription, capacity, workingHours are all private (-). This means that they are not accessivle for Building nor for Theater. Since you have no constructor and no setter, how can these properties be of any use? ANd since you have no public getter, how can these values be used in any showXxxx() operation of more specialized classes?
Since Building has no access to the private properties and has no other properties, how coud showArea() provide anything useful?
Finally, you're right about the overriding in Theatre. But the issues you've diagnosed for the missing size and its initialization are already true for Building.
So you will never be able to achieve your expected results on the console if you strictly stick to your diagram and add no other implicit operations. I hope this will not be a shock to you. Here the UML specification quote that backs my statement:
11.4.3.1: (...) A Class cannot access private Features of another Class, or protected Features on another Class that is not its ancestor.
Minor syntactical issues, you could improve:
The italic notation is meant for class names to document that they are abstract. It is no longer officially defined for abstract operations, although many (I say this because I do it myself) still use this notation. Using italics for operations which have an implementation is therefore utterly ambiguous.
void is no standard UML type. An operation returning void is just indicated without return type.
showEvents in Theater desserves a pair of braces ().
Complete your diagram
You could add the missing getters and setters. And you could define a constructor as explained in the UML specifications:
11.4.4: (...) A constructor is an Operation having a single return result parameter of the type of the owning Class, and marked with the standard stereotype «Create». The InstanceSpecification that is the supplier of the usage dependency represents the default value of the single return result parameter of a constructor Operation.
This would look like:
«Create» Place(...) : Place
You have now the means to complete your diagram and achieve the expected results.
Some more improvements may be desirable:
if Place implements no operation you should make it abstract, since it cannot be instantiated.
you may make the overriding explicit using the {redefines ...} in the diagram. But this is not necessary.
I guess that there is a missing relation to an Event class or interface, considering showEvents() and no other Events are in sight...
Reconsider your design
Is a theater a building? In my town, there is a building that hosts a mall AND a theater. So my advice would be to prefer composition over inheritance.
Your code and UML are not equal and your UML have some problems. In your diagram, Place is a concrete class and it is an abstract class by your code. There is no reason to have private attributes in the Place class because they can't be accessed by it's children, so their visibility should be replaced by protected (symbol in UML is #). The building class doesn't make anything but declare a method, so it could be replaced by an interface (in UML you can use a circle or use the interface stereotype) without any inheritance of Place, this solution would affect Theater that instead of being a child of Building, would become a child of Place that implements the Building interface.
About your code, the showArea method in the Theater class doesn't display any value, so why would you expect the 6000 value ? If you expected the 6000 value to come from the Place's capacity, first you would need a method (probably a setter) that sets the capacity, use this method in the Main class, then make capacity protected to be accessible by Theater and finally use it at the showArea method.

GWT generate class methods

In my project I have a series of Models which basically just contain data, and have getters and setters for that data (which has to match an API). I am trying to use GWT generators to generate the getters and setters (because they have some logic in them for setting default values and I don't want to have this typed out all the time.
For example, MyBusinessModel.java:
public class MyBusinessModel extends AbstractBusinessModel {
private Integer uid;
private String name;
//... and so on
}
I then create a public abstract class AbstractBusinessModel which has some implemented base methods. I had created a generator for this, AbstractBusinessModelGenerator extends Generator, which automatically creates all the getters and setters, but I keep getting errors about MyBusinessModel not being able to be a superinterface of MyBusinessModelImpl (the generated class) because it's not an interface.
Is there a way for me to generate classes like this (I can't make MyBusinessModel an interface because I need it to have private properties), or can I only generate interfaces (which become classes)?
The answer is to use setSuperClass on the ClassSourceFileComposerFactory instead of addImplementedInterface. I didn't realise that this existed. Now I do.

Generate GWT class without using GWT.generate

I have a series of models, each of which has some properties that are used by a generator to generate getters/setters automatically (because there is some logic relating to default values contained therein and I don't intend to write these manually for models with 20 odd fields).
When I'm instantiating the model, I use GWT.create(...), but sometimes I have classes which refer to my model, and these don't know that the setters/getters exist, because they are generated.
For example, I have my model:
public class MyModel extends AbstractModel {
private Integer uid;
private String name;
// ...
}
public interface JsonBinder<MyModel> {
public void bindDataToMode(MyModel model, JSONWrapper json);
}
Now JsonBinder<T> is also a generated class using GWT.create, but it refers to MyModel and not the generated MyModelImpl. Therefore on compile I get errors like setUid(Integer value) is not defined for class MyModel.
Is there a way to have the compiler replace all uses of MyModel with MyModelImpl?
This applies to both generics and method arguments, return types, etc..
No.
In your specific case, I'd rather generate the MyModelImpl et al. upfront, using whichever code generator you want (including, for example, an annotation processor) and then code against the generated classes directly.

How do you reproduce the behavior of const-pointers in Java?

I have a singleton class containing a bunch of control data that needs to be kept synchronized with the rest of my application. As a result, there are many times which I want another class to be able to read the information but not modify it. Currently, this singleton class has many public variables. I don't want to use getter and setter functions because they are wordy and annoying. Also, there are a lot of variables.
If my singleton class is called ControlData, I could create a second create a second class called ImmutableControlData, where it has all the same members, but they are declared final. Then, when retrieving my singleton, I would return an ImmutableControlData, rather than a ControlData object. However, this means that I need to constantly maintain the ImmutableControlData class as well as the ControlData class (annoying...)
If I had const-pointers, I would just return a const-pointer to my ControlData object. What can I do in Java, instead?
Java does not have const correctness like C++.
You could make an interface that declares the methods to read the data, but not the methods to modify the data. Make the class that holds the data implement this interface. Methods elsewhere in your program that should only read the data, should accept the interface, not the class, as the parameter type. For example:
public interface ReadablePerson {
String getName();
}
public class Person implements ReadablePerson {
private String name;
#Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
// Elsewhere...
public void someMethod(ReadablePerson p) {
System.out.println(p.getName());
}
Ofcourse, in someMethod you could still subvert this by casting p to Person, but at least it requires some conscious effort (adding the cast), which should alert the programmer that (s)he is doing something (s)he shouldn't do.
An advantage of this solution is that you don't have to make a defensive copy of the data.
First: If your Class has so many members, you should try to split the class into littler ones. Maybe you can summerize some variables eg.
ControlflowVariables
StateVariables
If you want to restrict the access to the variables you have to use getter. IDE can create getters and setters for you. The access to variables are the same:
singletonClass.variable is not worst then singletonClass.getVariable()
If you want to restrict the access only at some points in your code then create a final copy of tha variable
final int variable = singletonClass.getInstance().variable;
Personally, I would not try to control access in this way. There is nothing you can to do to prevent bad programmers from misusing your class. Even in C++, they could use a simple const_cast to remove your "protection" and modify the singleton any way they like.
Instead, I would restructure the code to make it easy for others to do the right thing and hard for them to get it wrong. Segregate the interface for ControlData into two separate interfaces: one for reading the object and one for updating it. Then simply provide the two interfaces where they're needed.

Java: Is there a way to you enforce a implementation of private methods?

I have 5 or 6 classes that I want to have follow the same basic structure internally. Really most of those that the classes should follow are just for the use of the function itself, so I really want these methods to be private.
Is there any way to achieve this? I know interfaces would work great but they won't take private members and won't allow you to redefine the scope in the implemented method. Is there any workaround for this?
Thanks
I think the closest you can get is using an abstract class with abstract protected methods:
abstract class A {
protected abstract void foo();
}
class B extends A {
protected void foo() {}
}
To define common logic, you can call the protected method from a private method in the super class:
abstract class A {
private void bar() {
// do common stuff
foo();
}
protected abstract void foo();
}
This way, you can allow subclasses to fill the private common template method with specific behavior.
Create an abstract base class that outlines the structure and common flow. Specify abstract methods for the steps in the flow that must be implemented by the inheriting classes.
Hmm, private functions can't be called by any other classes, even by subclasses. So what's the point in having private functions with the same name in different classes?
There is no way to enforce it at compile time, but you can write a unit test or a simple program to test for the existence of the methods using reflection.
I assume you are doing this to make the classes consistent for aesthetics/design reasons. If you are doing it for some other reason you should really use the abstract protected way others are suggesting.
Here is some code to get you started on such a tool/unit tests (you should improve the error messages at the very least, and I would really suggest unit tests rather then what I have here):
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class Main
{
public static void main(String[] args)
{
check(B.class, Modifier.PRIVATE, void.class, "doit", new Class<?>[] { int.class });
check(C.class, Modifier.PRIVATE, void.class, "doit", new Class<?>[] { int.class });
}
private static void check(final Class<?> clazz,
final int modifiers,
final Class<?> returnType,
final String name,
final Class<?>[] params)
{
try
{
final Method method;
method = clazz.getDeclaredMethod(name, params);
if(method.getModifiers() != modifiers)
{
System.out.println("modifiers do not match");
}
if(method.getReturnType() != returnType)
{
System.out.println("return type does not match");
}
}
catch(final NoSuchMethodException ex)
{
System.out.println("could not find method");
}
}
}
interface A
{
void foo();
}
class B
implements A
{
public void foo()
{
doit(0);
}
private void doit(final int x)
{
}
}
class C
implements A
{
public void foo()
{
doit(0);
}
private int doit(final int x)
{
return (5);
}
}
Create an outline 'common' class, with all your private methods on them.
Then create your 5 or 6 classes , each which have a field on there of type 'common'.
You won't be able to call the private methods of course (but you say these are really internal to the class) - you'll have to advertise some public methods to alter state as well of course.
public class common {
private method1() { ; }
private method2() { ; }
public other() { ; }
...
}
public class myclass1 {
common commonMethods;
}
public class myclass2 {
common commonMethods;
}
or even (assume 'common' is defined as above):
public class template {
common commonMethods;
}
public class myclass1 extends template {
...
}
So you get a (package-protected) 'commonMethods' field for 'free' on each of 5 or 6 subclasses.
After subsequent discussion on this thread, it appears the author doesn't actually want to share logic : just method signatures essentially , so this answer doesn't fit with that requirement.
While the interface methods themselves must always be public, you could make the interface package private and keep all of your Car (for example) implementations in the same package.
package com.some.car.pkg;
interface Car
{
public void gas();
public void brake();
}
Even though the methods are public, it doesn't matter since outside of the package com.some.car.pkg, Car is not visible. This way, all of your implementers would not be forced to extend an abstract class. The fact that you want common methods means truly private isn't the real solution, and IMHO, you want an interface, since it sounds like in your case an abstract class isn't quite right as there is no shared logic.
My 2 cents.
The "throw MethodNotImplementedException();" might be a useful construct.
If abstract protected really isn't protected enough, I wonder what the concern is. In any case, an alternative similar to monojohnny's would be to use the strategy pattern. This ensures that:
derived classes must define the behavior
derived classes can't access the behavior after defining it
instances can't access one another's behavior
E.g., with apologies for borrowing the car metaphor despite no automotive chops:
public interface GearBoxStrategy {
public void changeGear(int newGear);
}
abstract public class Car {
private GearBoxStrategy gearBox;
public Car(GearBoxStrategy g) {
this.gearBox = g;
}
public void accelerate(double targetSpeed) {
int gear = getTargetGear(targetSpeed):
gearBox.shift(gear);
}
}
public class AutomaticTransmissionCar {
public AutomaticTransmissionCar() {
super(new AutomaticTransmissionGearBoxStrategy());
}
}
public class ManualTransmissionCar {
public ManualTransmissionCar() {
super(new ManualTransmissionGearBoxStrategy());
}
}
Create an abstract base class with a method marked final that describes the common flow that includes your private methods. Marking it as final means that it can't be extended by subclasses and thus the business logic is enforced as long as your calling code utilizes it. Extension points can be created by marking methods as protected. For example say you have a class that represents a retail store.
private final void doTransaction() {
float amountDue;
// a protected or abstract method that extenders can override
Collection items = this.unloadShoppingCart();
for (Object item : items) {
// another protected or abstract method
amountDue += this.getPrice(item);
}
// your private method
amountDue += this.getSalesTax(amountDue);
}
Is it possible to make all the classes inherit from the same base class?
If so, one thing you could consider would be at runtime in the base class's constructor use reflection to validate that the subclass is following the rules you describe, and throw an exception if it fails your validation rules.
The naive implementation of this test of course would have significant performance issues, so you'd have to be pretty clever about the way you implement the test.
For a start, the test should only be run once for all instances of a particular subtype T. So, you would have to cache the validation information somewhere. One way to do this would be to use some kind of static (global) hash table in the base class keyed on the type of each subtype.
You would also have to perform some kind of thread safe synchronization around this cache. What you really need to avoid on this is a performance hit for reads. What I've done in a similar case before was use a combination of the double check locking pattern and the use of an immutable hashtable so that you only take a performance hit for locking when attempting to write to the hashtable (i.e. when you create the first instance of a particular subtype T).
I'm actually not experienced in Java, what I describe, I implemented in .NET, which is why I can't provide you with a code example, but all the concepts should be easily transferable to Java - everything I mention is (AFAIK) available on both platforms.
Take a look at XDepend, it uses reflection to create a database based on your compiled code.
http://www.xdepend.com
It's aimed at software architects who wish to be able to quickly check potentially large libraries of compiled code for potential problem areas. It has inbuilt reports and visualization for such things as relationships between classes, cyclomatic complexity, coupling etc. etc.
In addition, it includes an inbuilt sql like query language "CQL" (for "code query language"). Using CQL you can define your own reports. You probably should be able to use it to define a report for violations of the rules you describe. Also, you can embed CQL queries directly into your code using annotations.
I haven't looked into it, but have used it's .NET equivalent 'NDepend', and it's a very cool tool.
Of course, you could also write your own custom tool which uses reflection to check your specific rules. XDepend may still be worth looking at though - it should be a lot more flexible.
Here's an idea: write a simple text parser to check for the existence of the methods. Include it as a task in Ant. As long as you are insisting on some form of coding standard, some simple text-matching should do it, ie, simply look for the formatted signature in the required source files.
In a comment you wrote "Yes that is the whole point. I know they can be called different things but I don't want them to be."
Now, some people might just say "that's impossible" but like most things in programming, it's not actually impossible, it's just a lot of work.
If you really want to do this, you can create a custom Java Annotation for your class and then write an Annotation processor and call apt as part of your build process.
Like I said a lot of work, but it might be worthwhile if you want to learn how Annotations work.
Writing annotations is actually pretty simple. They work kind of like regular classes. For example, if you just want to mark a class for some reason you can create an empty or marker annotation like this
public #interface Car { }
Then in your Annotation Processor you can check to make sure Car has the right private methods.
I've written my own annotations, but I checked them at Runtime using the reflection API, rather then at build time. They are actually pretty easy.

Categories