#AutoValue - "cannot find symbol class Generated" Error - java

I am getting "cannot find symbol class Generated" while using the #AutoValue annotation.
public abstract class Office{
public static Office create(String cityName, String companyName, String regionName) {
return new AutoValue_Office(cityName, companyName, regionName);
}
public abstract String getCompanyName();
public abstract String getCityName();
public abstract String getRegionName();
}
Gradle dependency
compile 'com.google.auto.value:auto-value:1.0-rc1'
Also, how can add only selected properties to equals and hashcode function.

The problem is that you are using a version of Android that doesn't have the annotation javax.annotations.Generated (which was added in Java 6). You could add that manually as described in the answer to this question.
Concerning the question of excluding certain properties from equals and hashCode, there is currently no perfect way to do that. Often the desire to do this indicates a need to separate the properties that should be included into a separate class and use that in equals and hashCode. Alternatively, you could add non-final fields to the Office class and set them. For example, if regionName was not to be included, you could write something like this:
#AutoValue
public abstract class Office {
private String regionName;
public abstract String getCompanyName();
public abstract String getCityName();
public String getRegionName() {
return regionName;
}
public static Office create(String cityName, String companyName, String regionName) {
Office office = new AutoValue_Office(cityName, companyName);
office.regionName = regionName;
return office;
}
}
The main disadvantage is that regionName is not final, so you don't get the same guarantees about access to it from other threads as you do for the other properties.

Related

Determine which fields of a POJO are being accessed in a code

I have a huge (parent) POJO which is being used in some component. The POJO has individual fields as well as nested POJOs as well. Is it possible to determine what all fields/ nested fields from this POJO are being accessed in that component?
I was thinking about JUnits/ aspects but not sure if either would work. I've tried looking through SF/ and Google but could not find any relevant thread for this thing.
Say following is a sample POJO:
public class Student {
private String name;
private Date date;
private Subject subject;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Subject getSubject() {
return subject;
}
public void setSubject(Subject subject) {
this.subject = subject;
}
}
It has three fields name, date and subject, not all of which would be in use in my component. So I need to determine which are actually being used.
Edit:
Thanks Sharon for pointing out that the getter/setters were protected. I had just generated the class on the fly for the purpose of question and didn't notice the issue. Corrected now.
How the class is initialised: For the purpose of the component, objects will be created from Json/XML data and would have only getters being called.
As for static vs runtime analysis, I'd prefer to achieve it through static code analysis if that's possible otherwise runtime also is fine with me if that's easier.
As for using Decorator pattern, do we have anything without requiring existing code change? That's why I was thinking if JUnits could do this.
First of all, it is odd to see getter/setter methods that are protected. seems to me they need to be public?
Anyway, I would utilize the Decorator design pattern.
From the linked article:
The decorator design pattern allows us to dynamically add
functionality and behavior to an object without affecting the behavior
of other existing objects in the same class.
So, our decorated Student should inherit from the target class. All methods can log their usage and call super to invoke target operation. You didn't say how Student
is initialized, but anyway, you will want to modify that to create instances of LogUsageStudent
public class LogUsageStudent extends Student {
protected String getName() {
// log usage of getName()
return super.getName();
}
// etc
}

How does this class work or how can you use it?

I fell over a class which looks like this:
public final class DatabaseType{
public static final DatabaseType TYPE_LIMITED_TEXT = new DatabaseType();
public static final DatabaseType TYPE_UNLIMITED_TEXT = new DatabaseType();
public static final DatabaseType TYPE_DATE = new DatabaseType();
public static final DatabaseType TYPE_DECIMAL = new DatabaseType();
private DatabaseType(){
}
public String toString(){
return "DatabaseType";
}
}
I need to set the type but I want to understand what's happening here and I have no clue how this class works.
Whatever variable I use it will always return an empty DatabaseType, with no information. So I wonder how you can get use of such a class. Maybe there is a name for this type of class?
Basically, the class lists four enumerable constants, which you can use like this in method signatures
public DatabaseType getTypeOfDB();
In client code, you'll have a type-safe way to compare the constants:
if (getTypeOfDB() == DatabaseType.TYPE_LIMITED_TEXT) {
doSomething();
}
Even though the implementation seems a bit clumsy, it quite closely emulates a Java 5 enum, as Gimby pointed out in the comments. The good ideas in the design are the following:
The constructor is private, meaning only the public static final DatabaseType instances declared within the class can exist
The class is final so you cannot work around the above restriction by adding more constants in a subclass
The constant fields in the class have strong typing, i.e. they are not ints, but instead DatabaseTypes, which helps to eliminate bugs caused by typos or "magic numbers" in client code
The modern way to do the same would be using an enum instead:
public enum DatabaseType {
TYPE_LIMITED_TEXT, TYPE_UNLIMITED_TEXT, TYPE_DATE, TYPE_DECIMAL;
}
If you use call the function toString() you will always get the String : DatabaseType.
As i can understand you want to return the name of the variable you created that are DatabaseType.
Create a variable private String name; and modify the constructor like this:
private DatabaseType(String name){
this.name = name;
}
Also create a function
public String getName(){
return this.name;
}
Finally, when you create a databaseType object create it like this:
public static final DatabaseType TYPE_LIMITED_TEXT = new DatabaseType("TYPE_LIMITED_TEXT");

Automatic generation of immutable class and matching builder class of a Java interface

What tools or libraries exists for Java that will take an interface only with accessor method definitions and automatically generate an immutable object class and also a "builder" class for incrementally building new instances or changing existing instances by creating new ones?
Example input:
public interface Car {
String getModelName();
int getWheelCount();
}
Example output:
import javax.annotation.concurrent.Immutable;
import javax.annotation.concurrent.NotThreadSafe;
#Immutable
public final class ImmutableCar implements Car {
#NotThreadSafe
public static final class Builder implements Car {
private String modelName;
private int wheelCount;
public Builder() {
}
public Builder(final Car car) {
modelName = car.getModelName();
wheelCount = car.getWheelCount();
}
public ImmutableCar build() {
return new ImmutableCar(wheelCount, modelName);
}
#Override
public String getModelName() {
return modelName;
}
#Override
public int getWheelCount() {
return wheelCount;
}
public void setModelName(final String modelName) {
this.modelName = modelName;
}
public void setWheelCount(final int wheelCount) {
this.wheelCount = wheelCount;
}
}
private final String modelName;
private final int wheelCount;
public ImmutableCar(final int wheelCount, final String modelName) {
this.wheelCount = wheelCount;
this.modelName = modelName;
}
#Override
public String getModelName() {
return modelName;
}
#Override
public int getWheelCount() {
return wheelCount;
}
}
Immutables (http://immutables.github.io) annotation processor is the exact match for your needs. It is full-featured and very customizable (you know all those set vs with vs no-prefix wars, - use whatever you prefer). It can generate immutable implementation with builders for interfaces, abstract classes, annotations. In addition, it can generate builders to invoke static factory methods or POJO constructors and many other things.
#Value.Immutable
public interface ValueObject {
String name();
List<Integer> counts();
Optional<String> description();
}
// Compile using annotation processor and use it like this
ValueObject valueObject =
ImmutableValueObject.builder()
.name("My value")
.addCounts(1)
.addCounts(2)
.build();
Google have a tool called AutoValue that does this, except based on an abstract base class instead of an interface.
import com.google.auto.value.AutoValue;
class Example {
#AutoValue
abstract static class Animal {
static Builder builder() {
return new AutoValue_Example_Animal.Builder();
}
abstract String name();
abstract int numberOfLegs();
#AutoValue.Builder
abstract static class Builder {
abstract Builder name(String s);
abstract Builder numberOfLegs(int n);
abstract Animal build();
}
}
}
Another similar tool is Immutables; this is probably a closer match to the question, as it uses an interface and generates an immutable implementation and a builder.
Lombok allows code like this:
#lombok.Data
#lombok.Builder
public class ImmutableCar implements Car {
private final #lombok.NonNull String modelName;
private final #lombok.NonNull int wheelCount;
}
The lombok annotations are processed at compile time (JSR-269) to generate the full class. It is also possible to look at the generated code by 'delomboking' via a Maven plugin.
check out Eclipse Model2Text project and its subprojects, especially Acceleo and Xpand. they are generally used to generate EMF-based Java code for EMF models but they can be used to generate simple POJOs too.
however this functionality does not come out of the box: you'd have to create your own code generator and templates for it. see Accelelo tutorial .
EDIT:
one more idea - one so simple that it took me a day to realize it
you can use Velocity, Freemarker or similar template library (which are normally used for html generation). though still you need to make a model somewhere, in a .txt or .xml file for example. here's a tutorial on Velocity code generation.
I just created an eclipse plugin https://github.com/karajdaar/templator.
It generates code based on Freemarker templates. The context to the Freemarker template is a ICompilationUnit which allows fully access to named classes and their information. We are using it to generate DAOs for NoSQL databases, jersey client, tests, etc.
I think it can easily do what is required here.

Inherited enum redefinition

It is more complex than it sounds, but I think I am obliged to try something like it. I want to make an abstract parent class with a prototyping of an enum (I want to declare the enum with only one value probably that will be the default unitialized one and also declaring a couple of methods that I will be using from the subclass), then I want to class that will extend the abstract parent to actually intialize the very same enum (I know that this practically hides the parent enum) so that the kid class will define a set of items inside the enum, but keep the methods probably.
I do not know much about this level of abstraction so I will now describe the nature of my problem, in case there is a more practical solution:
I have a bunch of files that contain classes that implement a lot of commands based on enums. (e.g. class1 implements Observer has an update method that uses an enum-based switch to decide what command was picked, same applies for the other classes) I now want to abstract this whole thing in a way that I have an enum variable with the exact same name in all classes (e.g. CommandSet) so that I can have a generic method inside the parent that will be able to print a help list to my system using the inside methods of the enum. Now I know I can rewrite the exact same method in every class, but I want to abstract it so that others can keep on extending the library I am making!
Hopefully I am not too confusing or too confused and somone can help me! :)
Edit: Here is an idea of the code (Probably not right):
public abstract class Commands{
enum CommandSet{
// empty command, placeholder
null_command ("command name", "command description");
// the Strings used for name and description
private final String name;
private final String description;
// constructor
CommandSet(String name, String description){
this.name=name;
this.description=description;
}
// get parameters
public String getName(){
return name;
}
public String getDescription(){
return description;
}
}
public void showHelp(){
for (CommandSet i : CommandSet.values()) {
printf(i.getName(),":",i.getDescription());
}
}
}
public class StandardCommads extends Commands implements Observer{
// I want to change the enum here, just changing the values so that null_command ("command name", "command description") will get removed and I will add a dozen other values, but keep the methods that the parent had
// update inherited from Observer
#Override
public void update(Observable observable, Object object) {
// I want the commands inside the switch cases defined inside this class's enum
switch(CommandSet.valueOf(String.valueOf(object)){
case command1: doStuff1();break;
case command2: doStuff2();break;
...
case commandN: doStuffN();break;
}
// other methods
void doStuff1(){
...
}
...
void doStuffN(){
...
}
}
public class NonStandardCommads extends Commands implements Observer{
// Another set of commands here for the enum keeping the same methods it had in the parent
// update inherited from Observer
#Override
public void update(Observable observable, Object object) {
// Other set of commands inside this class used in the switch statement
switch(CommandSet.valueOf(String.valueOf(object)){
case Zcommand1: doStuffz1();break;
case Zcommand2: doStuffz2();break;
...
case ZcommandN: doStuffzN();break;
}
// other methods
void doStuffz1(){
...
}
...
void doStuffzN(){
...
}
}
Impossible: Java enums can neither extend another class nor be extended themselves.
They can however implement interfaces. Perhaps you can use that to your advantage.
There is something else about enums that may help you: enums are not immutable. You could change field values of the enums, however that would change them for the whole JVM.
Another approach maybe to pass your subclass instances into a method of the enum and have the enum use your subclass as a call back to get different functionality out of an enum for a different user of the enum.
Nope, you can't do that.
Java Enums run out of gas very quickly & definitely, when you want to add/extend more definitions or instantiate the enum instances, at a later time. (eg load them from database, configure them in an instance method, not just statically.)
Behaviour/ or logic in Java enums is kinda limited too -- you can define & set properties, but only what's statically initializable, and logic seems basic (you end up mainly just comparing references or ordinals, with the other defined enum constants).
What you can do:
You can implement an ancestor Command or AbstractCommand class, with a integer Code, and then subclass it to define concrete values/ additional codes/ load or configure instances, etc.
For further benefit, you get efficient switch & despatch (by Code) plus the ability to define further details/properties, instantiate commands as-needed, etc.
Essentially, this is how you used to define an Enum before Java supported them. Though you may be using them as value objects, rather than strictly static.
My expertise:
I've done extensive compiler & type-system work, tried enums for file-types and associated data/behaviour.. explored the outer limits, and reached the definite boundaries.
I also like being able to instantiate & return a new UnknownFileType("") as an answer, too. Enums can't do that.
Example:
(We'll despatch by String, not int -- since your code appears to be using Java 7. This makes command resolution easier, than requiring both a syntactical "name" and an internal integer "code".)
public static class Command {
protected String code;
protected String desc;
public String getCode() {return code;}
public String getDesc() {return desc;}
public Command (String code, String desc) {
this.code = code;
this.desc = desc;
}
public String toString() {return code;}
}
public class StandardCommands {
public static Command READ = new Command("READ", "read a record");
public static Command CREATE = new Command("WRITE", "create a record");
public static Command EDIT = new Command("WRITE", "modify a record");
}
public class FurtherCommands extends StandardCommands {
public static Command LIST = new Command("LIST", "list all records");
}
public class QueryCommands extends FurtherCommands {
public static class QueryCmd extends Command {
protected String search;
public String getSearch() {return search;}
// constructor..
}
public static QueryCmd QUERY_EXAMPLE = new QueryCmd("QUERY", "example", "query for specified string");
public static QueryCmd createQuery (String search) {
return new QueryCmd( "QUERY", search, "query for specified string");
}
}

issue about LCOM4 with Weld/CDI?

I'm new for both Sonar and Weld/CDI. I would like your help to advise further about the LCOM4 analyzed result with Weld/CDI. Firstly I create a simple java class as the following: -
-------------Source---------------
interface MyInterface1 {
String getName();
void setName(String name);
}
interface MyInterface2 extends MyInterface1 {
String getPhone();
void setPhone();
}
public interface MyPublishedInterface extend MyInterface1, MyInterface2 {
//There is no any definition, it just a collected capabilities
//which will be published to other package. Some capabilities
//may be hidden and use internally.
}
abstract class MyBean1 implements MyInterface1 {
private String name;
#Override
public String getName() {
return this.name;
}
#Override
public void setName(String theName) {
this.name = theName;
}
}
abstract class MyBean2 extends MyBean1 implements MyInterface2 {
private String phone;
#Override
public String getPhone() {
return this.phone;
}
#Override
public void setPhone(String thePhone) {
this.phone= thePhone;
}
}
public class MyPublishedBean extends MyBean2 implements MyPublishedInterface {
//There is no any coding, it just a collected capabilities
//which will be published to other package. Some capabilities
//may be hidden and use internally.
}
#Named
#RequestScope
public class MyBackingBean {
#Inject
private MyPublishedInterface myPublishedInterface;
//-----the business method, setter and getter here.
}
-------------Source---------------
After I've analyzed with the Sonar, it reports that the MyPublishedBean has a LCOM4>1 as
getPhone()Ljava/lang/String;
setName(Ljava/lang/String;)V
setPhone(Ljava/lang/String;)V
getName()Ljava/lang/String;
Previously I used to mark all method to be a "final" method, there is no any mentions about the LCOM4. Anyhow the system shows me the exception about Unproxyable since my class contains a final method. I had removed the "final", I faced the LCOM4 issue.
I'm not sure if I'm confused about Sonar, Weld/CDI, the class/interface design or all of them. Could you please help to advise further?
The Sonar docs explain LCOM4 quite well. The results you see are completely correct given the example you gave here.
These interfaces look like they are merely data holders with no logic. A bean with just getters and setters for properties will fully expect to have an LCOM value equal to the number of properties in the bean. LCOM4 is a metric meant to measure the cohesion of logic in a class. The logic of a pure data bean is only that the data is in some way related to each other. LCOM4 is therefore in this case an incorrect and misleading metric to use.
LCOM4 should also be completely independent of whether your methods are final or not.
Please note that LCOM4 > 1 indicates a suspect class. It does not mean that the class is wrong and should not be used to flag the class as bad. Once you find that the suspect class is okay, it is best to remove that class in some way from the metric (to avoid you building up a long list of warnings that you know should be ignored).

Categories