简体   繁体   中英

reuse of fields or methods for their names and for javadoc description

I am using struts 2 and getting benefit by its mechanism by which I can get and use request params while I declare the exact names as field variables of my class.

MyClass extends SomeOtherClass {
/** the user id*/
private int userId;
/** the user name*/
private String userName;

// /** java doc description for getters and setters here*/
//getters and setters for userId and userName here
}

mysite.com?userId=3&userName=sarah

The universe uptill here works fine and nice.


Now I have many ( Many ) of such classes that share same named field variables (with of-course different values but same name and same javadoc description).

I want to write the names and / javadoc description */ for them in one place.**

Now since I cant use inheritance as I am already extending from an other class, I tried to use Interfaces.

public interface MyInterface {
    /** description from interface for String s */
    String s = null;
    /** description from interface for int i */
    int i = -1;
    /** description from interface for boolean b */
    boolean b = false;

    /** description from interface for getB */
     boolean getB();

}

public class Class3 implements MyInterface {
    /** description from class 2 for int i */
    int i;
    /** description from class 2 for getB */
    private boolean getB(){
        return b;
    }
    /** description from class 2 for s() */
    private String s(){
        return null;
    }
}


public class Class1 implements MyInterface {
    String getS(){
        return s;
    }
}

Questions:

The java docs generated for class 1 or 3 do NOT show any fields or description for them. Why?

And any bright ideas for a better strategy considering struts params and declaring the common fields and its description at one place but using the same (with different values and getters and setters in each class)

在此处输入图片说明在此处输入图片说明

You can't have instance fields in interfaces, because interfaces don't have any state. The fields you added to the interfaces are actually public static final constants.

What you're trying to do won't work.

Class1 doesn't have any field described in the javadoc because it doesn't have any.

Class3: has one instance field i which is completely different (it's hiding it) from the static constant i defined in the interface.

If you want to reuse fields, getters and setters, your best bet is to use composition and not inheritance. Place all these common field in a class (let's say Address), and have a field of type Address in all the action classes that need to handle addresses..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM