variable referencing in getter method - java

Is the following declaration in getter method legal?
App.java
package com.abc.xyz.db.main;
public class App
{
public static String zipfilename;
........................
}
PatchFileDetailsForIndividualFilesInPatch.java
import com.abc.xyz.db.main.App;
public class PatchFileDetailsForIndividualFilesInPatch {
private String patchFileName;
public String getPatchFileName() {
return patchFileName;
}
public void setPatchFileName(String patchFileName) {
this.patchFileName = App.zipfilename;
}
.....................
}
Even though IDE is not complaining, yet I am feeling confused whether is this the correct way of passing variables declared in one class to a getter method in another class.
I am new to Java. I know this is an extremely rudimentary question but your guidance would help me :)
Regards

Related

Importing two utility classes with same name. Feature or useless?

For two utility classes with the same names, which contain only static methods, I proceeded as follows:
Simply imported the first
Created an instance of the second class.
Example:
package util1;
public class Utility {
public static void method() {
System.out.println("First Utility. static method");
}
}
package util2;
public class Utility {
public static void method() {
System.out.println("Second Utility. static method");
}
}
import util1.Utility;
public class Component {
private static final util2.Utility anotherUtility = new util2.Utility();
public static void usedByReflection() {
Utility.method();
anotherUtility.method();
}
}
Now I don't need to write a full second util-class name for invoke its methods, but maybe I did not foresee something...?
P.S:
The methods of the class Component are called through a reflection by a certain BlackBox. All the multithread-safe features are in BlackBox.
UPD: I have found better trick:
import util1.Utility;
public class Component {
private static final util2.Utility anotherUtility = null; // There are some changes
public static void usedByReflection() {
Utility.method();
anotherUtility.method();
}
}
Now I dont create new object, but is it possible to use it without any bugs?
IMO, this is confusing and could much more clearly be handled by something like:
public class CombinedUtilityComponent {
public static void usedByReflection() {
util1.Utility.method();
util2.Utility.method();
}
}
Or, better yet, in your code you can just fully qualify the class names and they become unique names without any confusing tricks.
Yes, this works. I wouldn't do it, though.
You're calling a static method as if it were an instance method. anotherUtility.method() has a useless reference to anotherUtility.
You also have an unnecessary instantiation of util2.Utility. This technique wouldn't work if the default constructor were disabled.

Why my access to non static string variable doesn't work

Why my access to non static string variable doesn't work. Try to do it and my IDE found it already but when I run it show "Cannot find symbol"
Please help me, Thank You.
public class Main
{
public static void main(String[] args)
{
testWrong obj = new testWrong();
System.out.println(obj.public_non_static()); //Doesn't Work
}
}
public class testWrong
{
public String public_non_static = "It is Public non Static";
public void in_non_static_method()
{
testWrong obj1 = new testWrong();
obj1.public_non_static(); //Doesn't Work
}
public static void in_static_method()
{
testWrong obj2 = new testWrong();
obj2.public_non_static(); //Doesn't Work also
}
}
You have a variable named public_non_static but you try to access a method with that name which does not work in Java.
on the other hand you should not get used to access variables in other classes directly since it violates the most important OO principle information hiding/encapsulation.
The same is true for getter/setter methods which should only be used on stupid data transfer objects (DTOs) or Value Objects which have no (business) logic.
You are accessing like a method :public_non_static();
Use this instead : obj2.public_non_static;
And since you are like very new to OOP, it's the best practice to not to use public keyword and you should make them private and make getters and setters for them.

Reflection VS static stuff

Recently I've been restructuring a Java code of mines trying to eliminate, wherever possible, static stuff (variables and methods) and replace it with better coding practices.
I also started studying reflection and noticed that it allows me to do some things1 that, at first, I could only achieve (or, at least, that's how I see it) with static calls or references.
However, while I've been reading that the use of static is not much recommended, it doesn't seem to be the same with reflection.
So, I'm asking: instead of making a method static and calling it like ClassName.methodName(), is it a legitimate use of reflection making it an instance method and invoking it by java.lang.reflect.Method.invoke()?
1 like dynamically accessing a class' content
Here's a code sample:
Hypothetic situation that works (but I don't want to make the method static):
import static java.lang.System.out;
public class Foo
{
private static boolean light;
public Foo()
{
turnOn();
}
public static void turnOn()
{
light = true;
}
public static void turnOff()
{
light = false;
}
public static boolean isGreenLight()
{
return light;
}
}
public class Boo
{
public Boo()
{
if (Foo.isGreenLight()) // I need to access Foo.isGreenLight() from here, but cur-
{ // rently that method is not static (it should be to do so)
out.println("Ok!");
}
}
}
public final class Main
{
public static void main(String[] args)
{
final Boo boo = new Boo();
}
}
Hypothetic situation that also should work (how it'd be using reflection):
import static java.lang.System.out;
import java.lang.reflect.Method;
public class Foo
{
private boolean light;
public Foo()
{
turnOn();
}
public void turnOn()
{
this.light = true;
}
public void turnOff()
{
this.light = false;
}
public boolean isGreenLight()
{
return this.light;
}
}
public class Boo
{
public Boo()
{
if ((boolean) Class.forName("Foo").getMethod("isGreenLight", null).invoke(new Foo(), null))
{
out.println("Ok!");
}
}
}
public final class Main
{
public static void main(String[] args)
{
final Boo boo = new Boo();
}
}
Expected output (untested):
Ok!
Using reflection is a code smell, especially if the intent behind what you're writing does not warrant it.
It is difficult to say much more without seeing code as it's all just guesswork.
I would:
enumerate the reasons behind why you had those static members in the first place
determine if the static modifier was in fact the right decision in the first place: i.e. should these be instance or class members? How might they be used by "clients" of the classes in question? What paradigm am I using? Functional or Object Oriented code. Does it satisfy DRY, SOLID and KISS programming practices?
consider if I'm over-engineering in the first place
More importantly:
I would design my code through tests first, which drives the design of your API through the eye of the user, with the added benefit that you have test coverage before you've even implemented. Often times when writing code this way I eliminate such questions because the solution is more obvious when thought from the perspective of a user rather than a designer. It becomes a question of pragmatism rather than satisfying architectural design goals and philosophies.

AspectJ: Access private fields?

I want to use an aspect to add getter and setter for a private id field. I know how to add a method through an aspect, but how can I access the private id field?
I thoght that I just have to make the aspect provileged. I tried the following code, but the aspect cannot access the id field.
public privileged aspect MyAspect {
public String Item.getId(){
return this.id;
}
A possibility would be to user reflection like shown in this blog post: http://blog.m1key.me/2011/05/aop-aspectj-field-access-to-inejct.html
Is reflection the only possibility or is there a way to do it with AspectJ?
Are you sure you can't ? I just tested and it ran. Here's my full code:
package com.example;
public class ClassWithPrivate {
private String s = "myStr";
}
==========
package com.example.aspect;
import com.example.ClassWithPrivate;
privileged public aspect AccessPrivate {
public String ClassWithPrivate.getS() {
return this.s;
}
public void ClassWithPrivate.setS(String str) {
this.s = str;
}
}
==========
package com.example;
public class TestPrivate {
public static void main(String[] args) {
ClassWithPrivate test = new ClassWithPrivate();
System.out.println(test.getS());
test.setS("hello");
System.out.println(test.getS());
}
}
If for some reason, that does not work for you, you can use reflection, or another way as described here:
https://web.archive.org/web/20161215045930/http://blogs.vmware.com/vfabric/2012/04/using-aspectj-for-accessing-private-members-without-reflection.html
However, according to the benchmarks, it may not be worth it.

Java - Statements / Conversions | Pulpcore

[please note this may require AS3 + Java knowledge]
Background Information:
I'm trying to build a game using Java + Pulpcore, but I'm fairly new to the scene. The game I'm building could possibly be more performance intensive than I thought, and I know Java would solve my problems with this, but there are a couple questions I have dealing with strict-types, etc.
Here is my code in AS3:
Main.as3
import org.tbmb.champions.Container;
import org.tbmb.zombies.ZContainer;
public class Main extends MovieClip {
// ******* temporary properties ******* /
private var blunder:Container = null;
// ******* ******* /
public function Main() {
init(); // initialize objects
}
public function init():void {
blunder = new Container(Blunder as Class);
} // end of class
}
Container.as3
package org.tbmb.champions {
import flash.display.MovieClip;
public class Container extends MovieClip {
public function Container(champ:*) {
} // end of constructor
} // end of class
} // end of package
Blunder.as3
package org.tbmb.champions.blunder {
import flash.display.MovieClip;
public class Blunder extends MovieClip {
public function Blunder() {
} // end of constructor
} // end of class
} // end of constructor
1.) How would I rewrite in Java?
blunder = new Container(Blunder as Class);
2.) How would I be able to accept any Classes in Java for the above line within my Container class?
public function Container(champ:*) {
I need to do this because I'm sending different champion classes (depending on what the user picks) to a containing class that will hold all their other classes (health, etc). I need my Container class to accept any Class rather than just one; what type would I use?
Here is what I have in Java so far:
ZomboPulp.java (Main Class)
import pulpcore.scene.Scene2D;
import org.tnpfk.champions.Container;
import org.tnpfk.champions.blunder.Blunder;
import pulpcore.sprite.FilledSprite;
import pulpcore.image.Colors;
public class ZomboPulp extends Scene2D {
FilledSprite background = new FilledSprite(Colors.WHITE);
Container container = null; // Container that contain's blunder,
// and all his objects (health, mana, etc)
public void load() {
this.initScreen(); // initialize main screen.
this.initObjects(); // initialize our objects.
} // end of load();
public void initScreen() {
add(background);
} // end of initScreen();
public void initObjects() {
container = new Container(Blunder as Class); // ERROR HERE
} // end of initObjects();
}
Container.java
package org.tnpfk.champions;
public class Container {
public Container(Object champ) {
} // end of constructor
} // end of class
Sorry for the lengthy post, and thanks for any help. By the way, I did check StackOverflow; and Google, but I was unable to find anything about this.
Thanks,
jvmpulp
Alrighty! I have no experience with PulpCore, but I do know both AS3 and Java, so I think I can answer your question. First off, I guess I don't 100% understand what you need to do with the champ object in the Container class, and I really don't understand why you were doing Blunder as Class instead of just passing an instance of Blunder. Either way, here's what I'd recommend with what you have as of now:
public void initObjects() {
container = new Container(Blunder.class);
}
As you can see, you can get a Class instance just by getting the class property of any class. Now, you have the right idea with using Object as the type for the Container constructor for any type. However, using Object is bad practice (use method overloading/more specific types instead), and it's not even required here. Getting the class property will always be of type Class, even though they represent different classes. So, rewrite the constructor as this:
public Container(Class champ) {
}
Then, do whatever you need to do with the class.
Now, that's basically a direct port, but it seems some of the things you're doing are bad practice. The whole system of passing a Class object seems irrelevant and unnecessary; why not just pass an instance of the object? For example, like so:
public class Container {
protected Champion champ;
public Container(Champion champ) {
this.champ = champ;
}
}
Now, make Champion an abstract class that contains the common methods for all the champions:
public abstract class Champion {
protected Something something;
abstract Something getSomething();
}
(Obviously, the variable/method shown here are just examples.) Then, have your individual Champion classes subclass Champion:
public class Blunder extends Champion {
public Something getSomething() {
return this.something;
}
}
Etc. Then, finally, do this:
public void initObjects() {
container = new Container(new Blunder());
}
Obviously, this is a basic example, and you don't have to take my advice. But it would probably be easier to do than the system you already had in AS3.

Categories

Resources