In Eclipse Luna, I want to change the content of the autogenerated methods, so I went to Window->Preferences->Java->Code Style->Code Templates->Code->Method body and I saw there this declaration:
// ${todo} Auto-generated method stub
${body_statement}
Is it possible to to change the ${body_statement} content?
Edit: #Duncan - I don't want my generated methods to return null but I want them to throw an exception that the method is not implemented. The reason why I want to change the ${body_statement} is because I want to change all occurrences by one edit and I don't want to go through all templates and inspect them one by one.
Just delete the invocation of ${body_statement} in your template
Here is my Method Body template which adds a TODO and an exception should the method be called:
// ${todo} Implement ${enclosing_type}.${enclosing_method}
throw new RuntimeException("Unimplemented Method ${enclosing_type}.${enclosing_method} invoked.");
Which when invokded after writing
int foo = doSomething();
Generates:
private int doSomething() {
// TODO Implement ScaledFraction.doSomething
throw new RuntimeException("Unimplemented Method ScaledFraction.doSomething invoked.");
}
${body_statement} is a "variable". Click on "Edit..." at the right side of the Code Templates list to edit a code template and use "Insert Variable..." to see a list of available variables.
The ${body_statement} variable is actually empty for new methods. If you want to provide some default-code for each new method, you can simple add that text above the ${body_statement}.
Adding real code below the variable in that template will not work, since ${body_statement} will be replaced by a return statement in some cases.
Related
I am working on a program that parses a Java file using the Java9 lexer and grammar from ANTLRs github. When parsing the file, I want to save each method name and the names of all methods called inside that method, in a HashMap<String, Set<String>>.
I use the listener pattern, where I use the method exitMethodDeclaration to get the method name and exitMethodInvocation to get the method invocations. The problem is that the two methods are invoked at different nodes in the parse tree, hence they take different context as argument. Therefore I am not able to call the method to get the invocations inside exitMethodDeclaration, to my knowledge. I attempted to build my own recursion, such that I could solve the type problem by passing methodDeclarationContext as argument to exitMethodInvocation. This would be very complex though, and I would like to use ANTLRs functionality.
With the code below, the hashSet for each method contains all method invocations for the entire file, and not just for the specific method.
private HashMap<String, HashSet<String>> methodCalls = new HashMap<>();
private HashSet<String> methodCallNames = new HashSet<>();
public void exitMethodDeclaration(Java9Parser.MethodDeclarationContext ctx) {
String methodName = ctx.methodHeader().methodDeclarator().identifier().getText();
methodCalls.put(methodName, methodCallNames);
}
public void exitMethodInvocation(Java9Parser.MethodInvocationContext ctx) {
try {
String m = ctx.methodName().identifier().getText();
methodCallNames.add(m);
} catch (Exception e) {
}
}
Any ideas on how to collect nodes of different context type inside the same method, visit a subtree inside a listener/visitor method or other ideas are much welcome!
You can create a Stack of ArrayLists.
Each time, you enterMethodDeclaration, push a new Empty ArrayList onto your Stack.
Each time you enterMethodInvocation (or exit... if you prefer), you can add the methodName to the ArrayList you have on stack.peek().
Whenever you exitMethodDeclartation stack.pop() you ArrayList, and it will have a list of all the method names you encountered in directly in that method call. And, the method name is right there in the Context parameter of exitMethodDeclaration
I have a method declaration with an annotation that is formatted by Eclipse Mars as follows:
#Override
void addLoadShiftingConstraints() throws NoSuchDataException {
//method body
}
I would like to not indent the method declaration:
#Override
void addLoadShiftingConstraints() throws NoSuchDataException {
//method body
}
Currently I have following formatter setting for the method declaration:
Right click on Project =>Properties=>Java Code Style=>Formatter
=>Edit active profile => LineWrapping => Method Declaration => Declaration => Wrap where necessary
If I would choose the option Do not wrap instead, the unwanted indent would vanish. However, I would like to keep the wrapping for long declarations.
Is this an Eclipse bug or is there an additional setting for the Annotations that I would have to change in order to avoid the indent?
This is indeed a bug (related). The workaround is to set the setting to "Do not wrap" as you describe or to add an access modifier like private.
(Can't comment due to insufficient reputation, but found this answer through search and it applies to a second situation.)
I faced a similar problem with indentation of local variables, which only took affect when a comment was placed after an annotation. #Stefan's answer worked for this also.
#SuppressWarnings("JavaReflectionMemberAccess") // implicit method Enum#valueOf(String)
Method method = class_.getMethod("valueOf", String.class);
was being reformatted to
#SuppressWarnings("JavaReflectionMemberAccess") // implicit method Enum#valueOf(String)
Method method = class_.getMethod("valueOf", String.class);
but was fixed with the addition of a final modifier:
#SuppressWarnings("JavaReflectionMemberAccess") // implicit method Enum#valueOf(String)
final Method method = class_.getMethod("valueOf", String.class);
The Java OpenGL GL interface contains about 2000 methods, for debugging purposes I would like to wrap an instance and delegate calls to it while doing some logging. The logging code can be pushed to the same method in each case, so the task of writing out the method implementations looks like it could be automated. An example of what I am trying to do:
import javax.media.opengl.GL;
public class GLErrorLogger implements GL {
private final GL backing;
public GLErrorLogger(GL delegateToMe) {
backing = delegateToMe;
}
private void checkErrorCode() {
// Log frame and thread details depending on gl state
}
/**
* Example of a method
*/
#Override
public int glGenLists(int arg0) {
checkErrorCode();
int retVal = backing.glGenLists(arg0);
checkErrorCode();
return retVal;
}
// rest of methods here...
}
In other words copy the method name and parameters (minus their types) into a call on the backing object, surround with calls to the logging method, and if there is a return type then assign the result to a variable of this type and return it at the end of the method.
I looked at creating a one shot eclipse code template to autogenerate the methods, but there wasn't an immediately obvious way to do pattern matching on the return type. Can anyone suggest a way to do this in Eclipse or any of its code generation tools to save me pulling out the regex toolkit?
You might want to use an Aspect to create the necessary bytecode for you instead of producing all the source code. Take a look at the Traceing Aspect example here: Traceing Aspect Example.
As an Alternative, you can create a Java Dynamic Proxy, if you do not want to use AspectJ as Thrid party Library. Please refer to Dynamic Proxy Tutorial
Use JDK proxies as suggested, or: use a Mock Framework like EasyMock or Mockito.
GL mock = EasyMock.createMock(GL.class);
EasyMock.expect(mock.someMethod()).andReturn(someValue);
// or, if you need to do more computing:
EasyMock.expect(mock.someOtherMethod()).andAnswer(new IAnswer<String>() {
public String answer() throws Throwable {
return "some value you calculate here";
}
});
EasyMock.replay(mock);
now you can use the mock Object for all methods you configured.
See the EasyMock readme for more info.
I have another question regarding checked exceptions. I have attempted to answer the question below.. Below my attempt is the original question and code. Could you let me know if I'm right or how I can change my attempt to make it correct. Kindest regards
public boolean checkMembership(MemberId memberId)
{
// Firstly the method is tried to see if it works.
try {
public boolean checkMembership(MemberId memberId)
}
// If it does not work, then the exception is called
catch (InvalidMemberIdException ex){}
}
The checkMembership method is part of the Membership class. Its purpose
is to validate the memberId it is passed as its parameter and then try to find it
in a list of members. It returns true if the memberId is found and false if not.
public boolean checkMembership(MemberId memberId)
{
if (!validate(memberId)) {
// An exception must be thrown.
…
}
// Further details of the check membership method are omitted.
…
}
If the memberId parameter to checkMembership is not valid then an
InvalidMemberIdException must be thrown. Rewrite the part of the
checkMembership method shown above to show how this would be done.
Remember, this is a checked exception. You must include detailed javadoc
comments for the method that conform to good stylistic conventions.
just add a
throw new InvalidMemberIdException("the id was invalid");
and update the javadocs.
edit -- i noticed them method as written is calling itself recursively (within the try catch block). You probably dont want to do this. Also, in the catch block you don't want to do nothing ('swallowing the exception' is usually bad). Put a log in there or something, or a comment that you are intentionally not doing anything.
I'd like to test that every method with a known prefix in a specific class is called during a particular test.
I can't work out a way to use mockito to stub out a method or how to verify that method has been called when the method name is not known until runtime.
The code below shows how I can get the methods I'd like to stub:
Method[] methodArr = customValidation.getClass().getDeclaredMethods();
loop: for (Method method : methodArr) {
if (method.getName().startsWith("validate")) {
// then stub out this method and check whether it gets called
// after we run some code
}
}
The question is, how can I stub them without know the method names until runtime?
Has anyone done anything like this before or have a good idea of how it can be done?
Many Thanks
This does not appear to be possible as of now. There is an unresolved enhancement request
For anyone who's interested, the solution I used was to use regular mocking to stub my methods:
UserBeanValidation userBeanValidation = Mockito.mock(UserBeanValidation.class);
Mockito.when(userBeanValidation.validateUserId(Mockito.anyString())).thenReturn(validationError);
I verified they were called once and incremented a count whenever one of the stubbed methods was executed. This count could be compared with a count of methods with a specific prefix to ensure all expected methods were called:
int totalMethodCount= 0;
Method[] methodArr = customValidation.getClass().getDeclaredMethods();
loop: for (Method method : methodArr) {
if (method.getName().startsWith("validate")) {
totalMethodCount++;
}
}
Assert.assertEquals(totalMethodCount, calledMethodCount);
This way I can be sure that all my methods are called... now to find out if they do what they're supposed to.