Java: get results from anonymous class operation - java

I want to do something like this:
public class ScadenzaService {
...
public List<Scadenza> tutteLeScadenze() {
List<Scadenza> scadenze = null;
txm.doInTransaction(new TransactionAction() {
#Override
public void perform() {
scadenze = dao.getAll(Scadenza.class);
}
});
return scadenze;
}
But I can't access scadenze in the inner class, since it's not final. However, final wouldn't help: it makes a constant.
What's the workaround?

Make scadenze final and initialise it to a new List. Inside your anon class you can still add to the list; being declared final does not prevent this.
public List<Scadenza> tutteLeScadenze() {
final List<Scadenza> scadenze = new ArrayList<Scadenza>();
txm.doInTransaction(new TransactionAction() {
#Override
public void perform() {
scadenze.addAll(dao.getAll(Scadenza.class));
}
});
return scadenze;
}

Related

How to initialize a value when creating an object in a static block

When creating the Racing class in ApplicationTest, I want to hand over the FixNumberBehavior class to the argument.
As shown below, to pass the argument to initialize FixNumberBehavior, but cannot pass the class field value to the static block.
The error message is as follows.
Variable 'isMove' might not have been initialized
FixNumberBehavior.java
public class FixNumberBehavior implements CarMoveBehavior {
private final boolean isMove;
private static FixNumberBehavior fixNumberBehavior;
static {
fixNumberBehavior = new FixNumberBehavior(); //error
}
public FixNumberBehavior(final boolean isMove) {
this.isMove = isMove;
}
#Override
public boolean moveBehavior() {
return isMove;
}
}
Racing.java
public class Racing {
private List<Car> cars;
private CarMoveBehavior carMoveBehavior;
public Racing(List<Car> cars, final CarMoveBehavior carMoveBehavior) {
this.cars = cars;
this.carMoveBehavior = carMoveBehavior;
}
public List<Car> getCars() {
return cars;
}
public void drive() {
cars.stream()
.forEach(car -> racingCondition(car));
}
private void racingCondition(Car car) {
if (carMoveBehavior.moveBehavior()) {
car.moveForward();
}
}
}
ApplicationTest
#ParameterizedTest
#CsvSource({"a,aa,aaa"})
void fixRandomNumberTest(String one, String two, String three) {
final List<Car> cars = Arrays.asList(new Car(one), new Car(two), new Car(three));
Racing racing = new Racing(cars, new FixNumberBehavior(true));
racing.drive();
racing.drive();
assertAll(
() -> assertThat(cars.get(0).getStep()).isEqualTo(2),
() -> assertThat(cars.get(1).getStep()).isEqualTo(2),
() -> assertThat(cars.get(2).getStep()).isEqualTo(2)
);
}
How can I initialize an object in the static block?
The problem is FixNumberBehavior has a final field that must be set in the constructor, or in an assignment on the field definition line.
While there is a constructor that takes a value for that field, the static block is not using that constructor, but instead a no-arg constructor.
Pass the value for that final field (isMove) in the new statement.
I am not sure why you want to overcomplicate things by
providing no-argument constructor when you already have constructor in which you let client decide if created instance of FixNumberBehavior will set isMove to true or false.
changing (in your answer) isMove from being final to being static. Those two keywords have different purpose:
final prevents reassigning new value to it
static makes this field a class field, not instance field, so even if you create two instances of FixNumberBehavior there will be only one isMove variable which they both will use (so you can't preserve in one instance state like isMove=true and in other state isMove=false).
What you are looking for is probably simply
public class FixNumberBehavior implements CarMoveBehavior {
private final boolean isMove;
private static FixNumberBehavior fixNumberBehavior = new FixNumberBehavior(true);
//set value you want here ^^^^
public FixNumberBehavior(final boolean isMove) {
this.isMove = isMove;
}
#Override
public boolean moveBehavior() {
return isMove;
}
}
I solved it by attaching static to the field.
Objects created in the static block are not identified when compiling. Therefore, the argument value to be transferred to the object you create in the static block must also be processed statistically.
package racingcar.model.domain;
public class FixNumberBehavior implements CarMoveBehavior {
private static boolean isMove;
private static FixNumberBehavior fixNumberBehavior;
static {
fixNumberBehavior = new FixNumberBehavior(isMove);
}
private FixNumberBehavior() {
}
public static FixNumberBehavior getInstance(){
return fixNumberBehavior;
}
public FixNumberBehavior(final boolean isMove) {
this.isMove = isMove;
}
#Override
public boolean moveBehavior() {
return isMove;
}
}

Creating a method that creates multiple lists inside a class

i wanted to know if you can create a method inside a class that can create more than 1 list
public class UnidadeSaude {
private String NomeUnidade;
public UnidadeSaude() {
}
public UnidadeSaude(String NomeUnidade) {
this.NomeUnidade = NomeUnidade;
}
public String getNomeUnidade() {
return NomeUnidade;
}
public void setNomeUnidade(String nomeUnidade) {
NomeUnidade = nomeUnidade;
}
void gravar(String NomeUnidade){
List<String> UnidadeSaude = new ArrayList<String>();
UnidadeSaude.add(NomeUnidade);
}
void ler() {
System.out.print(UnidadeSaude);
}
}
First: in Java, variable names are written in camelCase and Classes in PascalCase.
This is extremely important to difference between objects and Class references.
Second: I think you're trying to write names into a List in the gravar() method.
You can do it by having a static List in the class. You can add them to the list and then print them in the ler() method.
public class UnidadeSaude {
private String nomeUnidade;
private static List<String> nomeUnidades = new ArrayList();
public UnidadeSaude() {
}
public UnidadeSaude(String nomeUnidade) {
this.nomeUnidade = nomeUnidade;
}
public String getNomeUnidade() {
return nomeUnidade;
}
public void setNomeUnidade(String nomeUnidade) {
this.nomeUnidade = nomeUnidade;
}
void gravar(String NomeUnidade) {
nomeUnidades.add(NomeUnidade);
}
void ler() {
for (String nome : nomeUnidades) {
System.out.println(nome);
}
}
}
HOWEVER, I don't recommend this! It doesn't semantically make sense to store multiple objects into a class that represents a single object. You should ideally store them in a List outside that class

How can i access variable of one method into another?

I am creating android application. I have created one method testMethod1() then I have created another method testMethod2(). i have declare object of class in testMethod1(). How can i access object obj in testMethod2() ?
Public class TestClass() {
public void testMethod1() {
final ModalClass obj = new ModalClass();
testMethod2();
}
public void testMethod2() {
//I want to access 'obj' here
}
}
Edited quetion
I have created modal for listview. i want to set data into listview as bellow. but i can not be able to access locationDet into another method. its displaying can not resolve symbol 'locationDet'.
Public class TestClass() {
private List<LocationDetailModel> LocationDetailList = new
ArrayList<LocationDetailModel>();
public void testMethod1() {
JSONArray results = response.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
final LocationDetailModel locationDet = new LocationDetailModel();
locationDet.setTitle(obj.getString("name"));
testMethod2();
LocationDetailList.add(locationDet);
}
}
public void testMethod2() {
//I want to access 'obj' here
locationDet.setRating(results.getInt("rating"));
}
}
You have two choices:
1. You make the Variavble class known like this:
Public class TestClass(){
final ModalClass var = new ModalClass();
public void testMethod1() {
var = new ModalClass();
testMethod2();
}
public void testMethod2() {
//I want to access 'var' here
}
}
or you give your Var to test methode2 like this:
Public class TestClass()
{
public void testMethod1() {
final ModalClass var = new ModalClass();
testMethod2(var);
}
public void testMethod2(ModalClass var) {
//I want to access 'var' here
}
}
You can make the ModalClass var as a private attribute:
Public class TestClass(){
private final ModalClass var;
public void testMethod1() {
this.var = new ModalClass();
testMethod2();
}
public void testMethod2() {
//I want to access 'var' here
}
}
You can access the variables which are in scope and are visible. In your case you have a local variable which you wish to use in another method.
You can pass it as a method parameter. For this you will need to modify the signature of the method as below
public void testMethod2( LocationDetailModel locationModelDet ){
// now you acess the locationModelDet
}
and you can pass locationDet as parameter to the testMethod2 as testMethod(locationDet)
Another alternate option is instead of using local variable you may create a instance variable as
private LocationDetailModel locationDet = new LocationDetailModel();
Now in testMethod1() you need not create a local variable you can simply just set the title. For this you need not modify the signature of your testMethid2(). You will be able to acess the locationDet in both the method.

How to pass down the new operator in a method

For example, if I wanted to do something like this to call a method:
myLights.addLight(new Fluorescent(lumens));
in order to create a new object in the Fluorescent class and pass down the lumens data. How would I then set up the method to receive this?
Assuming method is not returning anything.
void addlight(Fluorescent a){
// your logic
}
In your Lights class create a method that accepts a Fluorescent object as an argument.
public void addLight(Fluorescent fluorescent){
// do something
}
Here is a basic example:
public class HelloWorld
{
public static void main(String[] args)
{
Light light = new Light();
light.addLight(new Fluorescent("300 lm"));
System.out.print(light.getLumen());
}
}
public class Light {
private String lumen;
public Light() {
}
public void setLumens(String lumen){
this.lumen = lumen;
}
public String getLumen(){
return this.lumen;
}
public void addLight(Fluorescent fluorescent) {
if(fluorescent.getLumen() != null) {
this.lumen = fluorescent.getLumen();
}
}
}
public class Fluorescent {
private String lumen;
public Fluorescent(String lumen){
this.lumen = lumen;
}
public void setLumen(String lumen){
this.lumen = lumen;
}
public String getLumen(){
return this.lumen;
}
}
Seeing that a Fluorescent is a Light, you might want to look in to inheritance.
Look here for some explanation
Java 101: Inheritance in Java, Part 1
public class Fluorescent() {
public Fluorescent(String lumens) {
// do something
}
}
public class Lights() {
public void addLight(Fluorescent fluorescent) {
// do something
}
}

Passing parameter to anonymous class in Java

i'm trying to write anonymous inner class
interface Face{
void seeThis(String what);
}
class Eyes {
public void show(Face f){}
}
public class Seen {
public void test() {
Eyes e = new Eyes();
e.show(new Face() {
#Override
public void seeThis(String what){
System.out.print(what);
}
});
public static void main(String[] args) {
Seen s = new Seen();
s.test();
}
}
How to call seeThis() and how to pass parameter to it?
Method seeThis() belongs to Face class, which instance is anonymous and thus cannot be reached without storing reference to it. If you want to store a reference, you can do this in the following way:
public class Seen {
public Face face;
....
this.face = new Face() { ... };
e.show(this.face);
And then,
Seen s = new Seen();
s.face.seeThis();
Now, regarding passing the parameter. You have two options - declare parameter outside of anonymous class and make it final in order to be reachable by this anonymous class, or replace anonymous class with normal one and pass the parameter to its constructor:
Approach one:
final int parameter = 5;
...(new Face() {
#Override
public void seeThis() {
System.out.println(parameter);
}
});
Approach two:
public class MyFace implements Face() {
private final int parameter;
public MyFace(int parameter) {
this.parameter = parameter;
}
#Override
public void seeThis() {
System.out.println(parameter);
}
}
Then,
...
e.show(new MyFace(10));

Categories

Resources