I am just curious on how people solve this. I often write the same type of code all the time. For instance:
new Thread() {
//...
//...
//...
//Change this line
//...
//...
}.start();
I keep changing the line where it says "Change this line" and then starting a thread. This change can be one line or a few lines. How would I go about compacting this code?
Well, I guess you could run your java files through the C preprocessor...
You can use the template pattern to create a base class that contains the common code. For example:
public abstract class ThreadTemplate extends Thread
{
public void run() {
//reusable stuff
doInThread();
//more resusable stuff
}
abstract void doInThread();
}
Then starting a thread with the boilerplate code is as easy as:
new ThreadTemplate{
void doInThread() {
// do something
}
}.start();
Also, a less elegant solution to save yourself some typing is to use the templating feature of your ide. You can find some info on setting them up in Eclipse here and you can find a list of useful ones at Useful Eclipse Java Code Templates
One technique is to put the code in an anonymous inner class, and pass that to a method that does the rest.
interface SomeInterface {
void fn();
}
executeTask(new SomeInterface {
public void fn() {
// Change this line.
}
});
private void executeTask(final SomeInterface thing) {
Thread thread = new Thread(new Runnable() { public void run() {
//...
//...
//...
thing.fn();
//...
//...
}});
thread.start();
}
Generally it isn't a good idea to extend Thread or other classes if it is unnecessary.
It's possible to use Java annotations to generate boilerplate code. Writing your own annotation processor is not hard.
If it is something that you use in many projects, I would set this up in your IDE. For instance I use eclipse and if you go to
Window->Preferences->Java->Editor->Templates you can setup your own templates, and then have them auto complete. For instance I always start typing sysout and then press tab, and eclipse has a built in template to replace that with System.out.println();
There are many pre-built templates in eclipse, so you could look at those for examples on syntax, if that is the IDE you use, if not there may be something similiar in other IDE's
This is very useful, and you could create one for any boiler code you find yourself writing a lot.
Nope, no macros. For this case, the closest you can get is to create new Runnable instance and pass it to either a function of your own creation or an ExecutorService, which will start the task for you.
With Java, there's no good way to get rid of this "boilerplate" code, mainly because you can't pass pointers to functions; everything needs to be an object.
In the case of a Thread, you can pass any object that implements Runnable to its constructor.
So, the solution is to create your own class:
public class MyClass implements Runnable {
void run() {
// change this line
}
}
Unfortunately, run isn't static, so you'll have to create an instance of MyClass first:
new Thread(new MyClass()).start();
You could also add variables to MyClass and a constructor so you can pass arguments to it.
Edit: If you need more than just the start method, you can also subclass Thread itself.
Related
Service interface:
public interface UserInterface {
void present();
void onStart();
void onStop();
}
I have two implementations: TextUserInterface and GraphicalUserInterface.
How can I identify the one I want to use when I launch my program? Source
private static void main(String[] args) {
ServiceLoader<UserInterface> uiLoader = ServiceLoader.load(UserInterface.class);
UserInterface ui = uiLoader.? //what to do to identify the one I want to use?
}
I was thinking of introducing an enum with the type of UI, so I could just iterate through all services and pick the one I'd like to, but isn't this approach just a misuse of services? In this case when I want to pick GraphicalUserInterface I could just skip the ServiceLoader part and just instantiate one. The only difference I see is fact that without services, I'd have to require the GraphicalUserInterface module, which "kind of" breaks the encapsulation.
I don't actually think that it would be a misuse of it. As a matter of fact, what you get from ServiceLoader.load(...) method is an Iteratable object, and if you need for a specific service, you will have to iterate through all the available instances.
The idea of the enum is not that bad, but I suggest that you take advantage of the Java stream and filter for the instance you need. For example, you might have something like that:
enum UserInterfaceType {
TEXT_UI, GRAPH_UI;
}
public interface UserInterface {
UserInterfaceType getTypeUI();
...
}
// In your main method
ServiceLoader<UserInterface> uiLoader = ServiceLoader.load(UserInterface.class);
UserInterface ui = uiLoader.steam()
.filter(p -> p->getTypeUI() == <TypeUIyouNeed> )
.findFirst()
.get();
That is open to a number of possibilities, for example you can put this is a separated method, which receives in input a UserInterfaceType value, and it can retrieve the service implementation based on the type enum value you passed.
As I said, that is just the main idea, but definitely you are not doing any misuse of the ServiceLoader.
I am using IntelliJ IDEA and I have problem with method usage finding.
Suppose I have interface Worker.
public interface Worker {
void startWork();
void endWork();
}
And I have two implementations.
public class Develper implements Worker {
#Override
public void startWork() {
System.out.println("Developer Start Working");
}
#Override
public void endWork() {
}
}
public class Qa implements Worker {
#Override
public void startWork() {
System.out.println("QA start Work");
}
#Override
public void endWork() {
}
}
I open the Developer class and trying to find usages of startWork().
I want only to view usage of the Developer.startWork() implemented method.
But when I find usages it shows both Developer and Qa.startWork() method usages. How can I avoid Qa.startWork() method usage when finding Developer.startWork() usages?
Using Ctrl+Shift+Alt+F7 (⌘+⇧+⌥+F7 for Mac) should show the prompt from Jim Hawkins answer.
See: https://www.jetbrains.com/help/idea/find-usages-method-options.html
When you search for usages of a method implementation with this dialog Ctrl+Shift+Alt+F7, IntelliJ IDEA will ask whether or not you want to search for the base method. With any other find usages actions such as Alt+F7 or Ctrl+Alt+F7, the base method will be included in the search results automatically.
I'm using IntelliJ IDEA 15.0.1 .
I think what you see when using the "find usages" functionality depends from the context.
If you place the cursor in method name Developer.startWork and invoke find usages , you should see a small dialog. You are asked "Do you want to find usages of the base method?" .
If you say "No", and in your sources you did only call the method via the base class or interface (Worker.start() in your example), IDEA doesn't show you any hits. Thats correct.
If you call the overridden method via Developer.startWork() , and press "No" in the dialog, then you will see the usages of the specific implementation.
Update:
After reading the answer from #JimHawkins, I think the elephant is still in the room :) The question is, do you want to see where Developer.startWork() is actually called, or do you want to see where it is statically referenced?
Eg:
Developer developer = new Developer();
developer.startWork(); // you want to find only this?
Worker worker = developer;
worker.startWork(); // ..or this as well?
The find usages method can only tell, where a given method is statically referenced, but not where it is actually used (that is determined runtime via the mechanism of polymorphism).
I have to develop an "generic" wigdet for a GWT/GXT project and to do so I need to create an instance of an object which type is unknown. I found an approach that works perfectly in dev mode but as soon as I try to compile my project and deploy it I get an Only class literals may be used as arguments to GWT.create() error.
Here is a sample of what I do:
public class GenericEditableGrid<M> extends Grid<M>{
private final ToolBar toolBar = new ToolBar();
private final TextButton newItemButton = new TextButton();
protected GridInlineEditing<M> editing;
private final Class<M> clazzM;
public GenericEditableGrid(Class<M> parametrizedClass, String gridTitle, ListStore<M> listStore, ColumnModel<M> cm) {
super(listStore, cm);
clazzM = parametrizedClass;
// ... then I create my widget
bind();
}
private void bind(){
newItemButton.addSelectHandler(new SelectEvent.SelectHandler() {
#Override
public void onSelect(SelectEvent selectEvent) {
editing.cancelEditing();
// it is the folliwing line which is the problem obviously
M element = GWT.create(clazzM);
getStore().add(0, element);
int index = 0;
editing.startEditing(new Grid.GridCell(getStore().indexOf(element), index));
}
});
}
}
And this is how I use it in my subclasses:
super(InternationalString.class, gridTitle, new ListStore<InternationalString>(isprops.key()), buildColumnModel());
Basically, I would like to know what the problem is exactly with this approach and eventually how I should do to make it well.
Please note that my concern is not just to make it work, but more to do it the right way. As I could just avoid the problem using an abstract method which would handle the GWT.create() method in the daughter classes. But this is not the design I want, it just doesn't look right.
What I don't get also is what's the difference between doing this:
MyClass e = GWT.create(MyClass.class);
and:
Class<MyClass> clazz=MyClass.class;
MyClass e = GWT.create(clazz);
Because as far as I am concerned I think this is basically what I am doing and it looks like the same thing. Isn't it?
There's a well-worded explanation in this forum:
As the error message indicates, only class literals may be passed to the GWT.create method. The reason for this is that all GWT.create calls are basically turned into constructors at compile time, using the deferred binding rules for your module. As a result, all classes must be decided at compile time - your code requires that the at runtime the class is decided. This is too late, and so cannot be compiled.
GWT is not proper java, and so cannot be always treated as java. This is one such example of things that cannot be done in gwt. ...
What is it you are trying to do? Either you are making it far more complicated than it needs to be, or you need to write a generator to do it instead of taking this approach.
For debugging purposes I need to keep track of a Class attributes changes.
For example consider the following class:
class Test {
int myInt;
String myString;
...
public void setMyInt(int a) ...
public void setMyString(String s) ...
public printDebugLog();
}
void main() {
Test t = new Test();
t.setMyInt(5);
t.setMyString("Hello");
t.printDebugLog();
}
I want to output to be something like:
myInt => 5
myString => Hello
The easy solution is to create logs instantly. i.e. adding a Log function as follow:
void Log(String s) {
System.out.println(s);
}
and then code the set functions like below:
void setMyString(String s) {
myString = s;
Log("myString => " + s);
}
this requires all the set functions to be written variously and I wonder if there are any better solution for such matter. For example it might be easier (if possible) to create a SetValue function which accepts two variables and set the first attribute to the value of the second object. or something like this.
Any idea?
To do this you should wrap your class with orthogonal code that performs logging.
Since your class does not implement interface you cannot use dynamic proxy, so you have to use one of solutions that use byte code engineering.
The strongest solution I know is AspectJ. But probably you even do not need it. You can use Javassist or CGLIb - the byte code engineering libraries that allow creating proxies that wrap classes, so you can add code that performs logging.
You can use AOP to intercept the setter methods and log when they are called. A quick google should give you a few examples.
If you debug via JPDA,
you can create a Breakpoint
on a field you like to watch.
So, here's an example. I have a library in the package HTTP. I define sub-sections of the library in e.g. the package HTTP.TCPProtocol. Now I want to use TCPProtocol from the HTTP package, which means I have to make the TCPProtocol functionality public. At the same time, this functionality should not be exported to users of the library.
How do I do this? I don't want to shove my whole library into one package, as I feel the separate sub-packages really make the code more structured and navigation easier in eclipse. But browsing around, I couldn't find a method to expose functions within my project, but not export them outside my project.
EDIT: In light of me being able to come up with a better example, I'm updating the OP.
One simplistic approach is to whitelist your 'utility' methods so they take a caller instance of a certain type only.
package gameengine;
interface Whitelisted {} // marker
Then your method:
public void myMethod(Whitelisted caller, String arg)
And to invoke:
package gameengine.network;
class Foo implements Whitelisted {
...
Someclass.myMethod(this, "foo");
Check the caller's class to lock out all unwanted callers. The caller's class can be obtained from the stacktrace. In the example below, only instances of Bar will trigger the system.out.println, all all other will get an exception. You can even do package-level checks this way. Make sure that all allowed caller classes methods are not public, or they can call the doSomething method indirectly. You can even do deeper checks, by inspecting the stacktrace further.
Be aware though, that a skilled develper can circumvent anything you try do do in this matter. No solution is really "secure".
package one.two;
import one.Bar;
public class Foo {
public void doSomething() {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
StackTraceElement stackTraceElement = stackTrace[2];
String className = stackTraceElement.getClassName();
if (Bar.class.getName().equals(className)) {
System.out.println("jay!");
} else {
throw new RuntimeException("not allowed");
}
}
}
package one;
import one.two.Foo;
public class Bar {
void makeCall() {
new Foo().doSomething();
}
public static void main(String[] args) {
new Bar().makeCall();
}
}
Without seeing your dependencies, the only real advice the community can give you is to refactor your code. If something in your networking package needs to know about your game engine, it seems like you have a leaky abstraction. Hard to say without seeing your code.