Preprocessor variables in Java - java

I am developing with GWT and share a codebase with an Android developer. Some functions we want to share take speciffic arguments like "Drawable" under Android and "Image" under GWT.
Is it possible to use a preprocessor variable as in C++:
#ifdef ANDROID
public void DrawImg(Drawable img);
#elif GWT
public void DrawImg(Image img);
#endif
The solution we are testing is a Generic like this:
interface DrawImgInterf<T extends Object> {
public void DrawImg(T img);
}
However using a preproccesor variable seems better. Is there such a thing in Java?

No, there's nothing like that in normal Java. You could run a preprocessor of course, but that will make it painful to develop the code. (Anything like an IDE which expects the code to be "normal" Java is going to get confused.)
Have you considered using an interface instead, which abstracts out the common operations, and binds to the appropriate real type at execution time? That won't always work (as adding a proxy breaks situations where object identity is important) but in some cases it can be helpful.

No, there are no preprocessor variables in Java.

for such cases it is the best way to use a preprocessor
I used it for my J2ME developments http://code.google.com/p/java-comment-preprocessor/wiki/ExampleOfUsageForJ2ME

Java+ is a preprocessor which can perform substitution using resource bundles:
public static void
main(String[] args)
{
System.out.println({{
The answer,
my dearest,
is {{computeAnswer()}}.
}});
}
static String computeAnswer()
{
return {{my computed answer}};
}
References
java+.tgz
java+.dmg

Employing Visitor Pattern here, is making sense to me. For example,
interface ImageVisitor {
void visit(GWTImage image);
void visit(AndroidImage image);
}
interface IImage {
void accept(ImageVisitor visitor);
}
class GWTImage implements IImage {
..
public void accept(ImageVisitor visitor) {
visitor.visit(this);
}
..
}
class AndroidImage implements IImage {
..
public void accept(ImageVisitor visitor) {
visitor.visit(this);
}
..
}
class GWTImageVisitor implements ImageVisitor {
public void visit(GWTImage image) {
Image img = image.getImage();
..
}
}
class AndroidImageVisitor implements ImageVisitor {
public void visit(AndroidImage image) {
Drawable drawable = image.getDrawable();
..
}
}

Related

java: how jna callback function works

I'm using a native library coded in C or C++, after a lot of multiple tests i successed to make it work, but i'm not sure if what i do correspond to the correct coding rules, and some parts are not clear for me.
So my question is : could you confirm and complete what i understood.
Thanks
the C prototype function is:
typedef void (*pfHook) (const char *pText);
and the function to set the callback function is:
short LogHookEx(void (*pfHook) (const char*));
So i created an interface for my native dll like that:
So if i understood "interface pfHookCallback" correspond to the C prototype function and "sCscSetApiLogHookEx" is a classic method from my native dll.
public interface Reader extends Library {
Reader INSTANCE = (Reader) Native.load((Platform.isWindows() ? "ReaderDll" : "c"),
Reader.class);
interface pfHookCallback extends Callback {
void invoke(String pText);
}
short LogHookEx(pfHookCallback pfHook);
}
The part that i understand less, is the part that i include in my "main":
public class Principal {
public static void main(String[] args) {
Reader.pfHookCallback pfHook = new Reader.pfHookCallback() {
public void invoke(String pText) {
System.out.println(pText);
}
};
res = Reader.INSTANCE.LogHookEx(pfHook);
To be more clear this callback function is used for tracing from an hardware device.
As described above, it's working, but it's not cleat for me.
And another question is , the goal of my code is to save the logs (so the pText string) into a file. Is there a best practice to do that, because if i create buffered writer, i don't know if it's good or not to do something like that:
public class Principal {
public static void main(String[] args) {
Reader.pfHookCallback pfHook = new Reader.pfHookCallback() {
public void invoke(String pText) {
bw.write(pText);
bw.close;
}
};
res = Reader.INSTANCE.LogHookEx(pfHook);
My question is i don't know if it's really good to open and close a file very quickly every time there is a log to be saved ?

Is this still follow Dependency Inversion Principle when implement multiple interface?

sorry for the long question and also my English.
I'm reading an article about DIP. I will summarize the code in here.
interface CoffeeMachine() {
void brewFilterCoffee();
}
interface EspressoMachine() {
void brewEspressoCoffee();
}
They create two different CoffeeMachine. BasicCoffeeMachine and PremiumCoffeeMachine. They both have the same feature is brewFilterCoffee(); so they put it on the CoffeeMachine interface
class BasicCoffeeMachine implements CoffeeMachine {
#Override
void brewFilterCoffee() {
System.out.println("brewing filter coffee...");
}
}
// this one can make Espresso
class PremiumCoffeeMachine implements CoffeeMachine, EspressoMachine {
#Override
void brewFilterCoffee() {
System.out.println("brewing filter coffee but in premium way...");
}
#Override
void brewEspressoCoffee() {
System.out.println("brewing espresso coffee...");
}
}
When they create CoffeeApp, it accepts CoffeeMachine interface in the constructor and uses it to prepareCoffee()
class CoffeeApp {
CoffeeMachine machine;
public CoffeeApp(CoffeeMachine machine) {
this.machine = machine;
}
public void prepareCoffee() {
machine.brewFilterCoffee();
}
}
In the Main class.
class Main {
public static void main(String[] args) {
PremiumCoffeeMachine premiumCoffeeMachine = new PremiumCoffeeMachine();
CoffeeApp app = new CoffeeApp(premiumCoffeeMachine);
app.brewFilterCoffee();
}
}
I left confused here because they didn't mention how they use brewEspressoCoffee() in CoffeeApp.
So I go ahead and modify CoffeeApp like this:
class CoffeeApp {
public void prepareFilterCoffee(CoffeeMachine machine) {
machine.brewFilterCoffee();
}
public void prepareEspressoCoffee(EspressoMachine machine) {
machine.brewEspressoCoffee();
}
}
In the Main class, if I want to brewEspressoCoffee(), I just create an instance that implements EspressoMachine
class Main {
public static void main(String[] args) {
PremiumCoffeeMachine premiumCoffeeMachine = new PremiumCoffeeMachine();
CoffeeApp app = new CoffeeApp();
app.brewEspressoCoffee(premiumCoffeeMachine);
}
}
Is this still the following DIP? And is there any better way to approach rather than this example? Any example would be appreciated.
Thank you!!
I think you've captured the essence of the DIP, which is that you can always insert an interface to invert the direction of a dependency.
Beyond just following the DIP, there is also the principle of Information Hiding to consider here. We often think of IH as applied to data, but it applies to dependencies as well.
In the original CoffeeApp, the client (customer) has no dependency on EspressoMachine and an indirect (transitive) dependency on CoffeeMachine. In the modified CoffeeApp, the client has direct dependencies on both Machine interfaces.
These dependencies are on abstractions, so the DIP is satisfied; but it begs the question, if CoffeeApp exposes its dependencies to its clients, then what is its purpose? Clients can invoke those dependencies directly. By passing on its dependencies, the CoffeeApp becomes useless.

Java extension methods for LiveData

In Kotlin there's an extension method observeOnce (https://code.luasoftware.com/tutorials/android/android-livedata-observe-once-only-kotlin/) which is the behaviour I'm looking to replicate in Java. It's to my understanding from googling that you can't use Kotlin extension methods in java (may be wrong), so I've got two options of using SingleEventLiveData which I've implemented and am not keen on, and removing my observer once used;
final LiveData<List<String>> stringsLiveData = mViewModel.getStrings();
stringsliveData.observe(getViewLifecycleOwner(), strings -> {
// Do stuff with data here
stringsLiveData.removeObservers(getViewLifecycleOwner());
});
Is there an equivilant method that can be used as the link above so;
mViewModel.getStrings().observeOnce(getViewLifecycleOwner(), strings -> {
//Do stuff here
});
Edit: As per the accepted answer below (modified to compile) I've got;
class LiveDataUtils {
public static <T> void observeOnce(LiveData<T> liveData, Observer<T> observer) {
liveData.observeForever(o -> {
liveData.removeObserver(observer);
observer.onChanged(o);
});
}
}
and a simple usage of this;
LiveDataUtils.observeOnce(
mViewModel.getStrings(),
strings -> {
// Do some work here
}
);
Every Kotlin extension function is resolved statically, which means that you can do the same in Java by using static functions. It is not as readable or as intuitive as the extension functions, but it does the same job.
Create a util class with a static method:
public class LiveDataUtils {
public static <T> void observeOnce(LiveData<T> liveData, Observer<T> observer) {
liveData.observeForever(new Observer<T>() {
#Override
public void onChanged(T t) {
liveData.removeObserver(this);
observer.onChanged(t);
}
});
}
}
I haven't tested the code, so it might have some errors. The point was to show you how you can replace extension functions in Java.
EDIT: Updated according to follow up by #Marek Potkan, since this is the accepted answer. As I mentioned, I haven't tested the code and I provided a wrong reference by mistake.
#deluxe1 answer wouldn't work. It is removing observer called observer, but that's not the one which is used in the observeForever method. Expanded version should be used instead of the lambda function here:
public static <T> void observeOnce(LiveData<T> liveData, Observer<T> observer) {
liveData.observeForever(new Observer<T>() {
#Override
public void onChanged(T t) {
liveData.removeObserver(this);
observer.onChanged(t);
}
});
}
I have tested both approaches.

Java: Using a class as an parameter to describe a setups

I couldn't think of a good way to name this. Basically I'm have a program where I want to have a default "pattern" almost I guess of how something should function. But I wanted to allow the use to create their own implementation (This is like an API) of the class and use that as a parameter instead, with the functionality inside. Is this the most efficient way to do it? If you don't understand that bad description here is an example.
public class SimpleStyle extends AbstractStyle {
public void personalizedImplementation() {
// manipulate the program this way
}
}
Then in the method
public static void do(Class<? extends AbstractSyle> style) {
// Use reflection in herre to get the implementation and do it
}
Is there a better and more efficient way to do something like this
You should not use reflection for this task if you can avoid it. It is less readable and more error-prone than well designed interfaces.
The basic solution (I’m not sure whether you already considered it) is to simply pass instances of AbstractStyle to your method:
public static void doSomething(AbstractStyle style) {
style.personalizedImplementation();
}
public static void main(String[] args) {
do(new SimpleStyle());
}
If you cannot use this approach – this depends on the specific use case – you could define an additional interface that handles the creation of the AbstractStyle instance:
public interface StyleFactory {
AbstractStyle createStyle();
}
public class SimpleStyleFactory implements StyleFactory {
#Override
public SimpleStyle createStyle() {
return new SimpleStyle(/* ... */);
}
}
public static void doSomething(StyleFactory styleFactory) {
AbstractStyle style = styleFactory.createStyle();
style.personalizedImplementation();
}
public static void main(String[] args) {
do(new SimpleStyleFactory());
}
Note: do is a Java keyword, so it can’t be used as an identifier. I used doSomething instead.

Java Passing in Type as Function Parameter

I come from a Python background and in Python you can pass in the type of an object as a parameter. But in Java you cannot do this, any tips on how to get something like this working?
private void function(Type TypeGoesHere)
Stock s = new TypeGoesHere();
s.analyze();
}
Java does not support Python’s way of referencing functions and classes. To achieve this behaviour, you have to use two advanced techniques: generics and reflection. Explaining these concepts is beyond the scope of a SO answer. You should read a Java guide to learn about them.
Yet here is an example how this would look like, assuming that the given class has a no-argument constructor:
public <T extends Stock> void analyzeNewStock(Class<T> clazz) throws Exception {
Stock s = clazz.newInstance();
s.analyze();
}
Then call this function with analyzeNewStock(MyStock.class).
As this is a rather complicated and error-prone approach, you’d rather define an interface that creates Stock instances:
public interface StockProvider {
Stock createStock(String value);
}
public class MyStockProvider implements StockProvider {
private final String valueTwo;
public MyStockProvider(String valueTwo) {
this.valueTwo = valueTwo;
}
#Override
public Stock createStock(String valueOne) {
return new MyStock(valueOne, valueTwo);
}
}
public class MyOtherClass {
public void analyzeNewStock(StockProvider provider) {
provider.createStock("Hi!").analyze();
}
public static void main(String[] args) {
analyzeNewStock(new MyStockProvider("Hey!"));
}
}
In Java you can pass a Class. You can do it like this:
private void function(Class c)
This is not very common procatice though. You can probably get wha you need by looking into Strategy pattern, or proper use of Object Oriented Programming (polymorphism).
If you are looking for a way to build some objects, look into Factory pattern.
If you want to create a generic class- look into this detailed answer: https://stackoverflow.com/a/1090488/1611957
You could use generics. For example:
private <T> void function(Class<T> clazz) {
try{
T t = clazz.newInstance();
//more code here
}catch(InstantiationException | IllegalAccessException ex){
ex.printStackTrace();
}
}
The Class<T> clazz shows what type to instantiate. The try/catch is just to prevent errors from stopping your code. The same idea is expanded in this SO post. More info here.
However, I'm not really sure why you would want to do this. There should easily be a workaround using a simple interface. Since you already know that you want an object with type Stock, you could pass an implementation of the interface. For example:
//interface to implement
public interface Stock {
public void analyze();
}
//rewrite of function
private void function(Stock s){
s.analyze();
}
And using two ways to call function:
//first way
public class XYZ implements Stock{
public void analyze(){
//some code here
}
}
//calling the function
function(new XYZ());
//second way
function(new Stock(){
public void analyze(){
//your code here
}
});

Categories

Resources