Categories
discuss

Same method for multiple classes that implement the same interface

Sorry I really didn’t know how to title the question, here’s the problem…

I have an interface and multiple classes that implement the interface. The implementation of some of the methods in the interface are exactly the same in every implementing class. I feel like there should be a way to simplify this so I don’t have to write the same code every time. Example:

public interface Foo {
    String getName();
}

public class FooImpl1 implements Foo {
    private String name = "foo name1";

    public String getName() {
        return name;
    }
}

public class FooImpl2 implements Foo {
    private String name = "foo name2";

    public String getName() {
        return name;
    }
}

So to break down..

  1. is there a way to put the code for getName in one place and each class has it’s own name variable?

  2. is there a way to make getName static so I don’t have to create a new instance

Have better ideas?

Answer

Use an abstract class and initialize the field in the constructor:

public abstract class Foo {

 protected String name;

 String getName() {
  return name;
 }
}

public class FooImpl1 extends Foo {

 public FooImpl1 () {
  name = "foo name1";
 }
}

public class FooImpl2 extends Foo {

 public FooImpl1 () {
  name = "foo name2";
 }
}

JB Nizlet pointed out that it would be cleaner to do something like this:

public abstract class Foo {

protected String name;

public Foo(String newName) {
    name = newName;
}

 String getName() {
  return name;
 }
}

And then call super("foo name 1") in the subclasses.

As @Peter Lawrey said, if you already have an interface or want one for some other reason:

public interface IFoo {
 String getName();
}

public abstract class Foo implements IFoo {

 protected String name;

 String getName() {
  return name;
 }
}
Categories
discuss

SDK Location not found in android studio

I have just imported my eclipse project in android studio. it keeps my saying that

Error:SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable.

I have seen some tutorials of editing local.properties files but it didnt work. here is my project.properties file:

sdk.dir=E:\Mod Eclipse\adt-bundle-windows-x86_64-20130219\sdk

Actual directory of my folder is :

E:Mod Eclipseadt-bundle-windows-x86_64-20130219sdk

Answer

You should also change it on Project Structure.

  • Close the current project and you’ll see pop up with dialog which will then proceed to Configure option.

    Configure -> Project Defaults -> Project Structure -> SDKs on left column -> Android SDK Home Path -> give the exact path as you did on local.properties and select Valid Target.

There you go.

Categories
discuss

How can I mock private static method with PowerMockito?

I’m trying to mock private static method anotherMethod(). See code below

public class Util {
    public static String method(){
        return anotherMethod();
    }

    private static String anotherMethod() {
        throw new RuntimeException(); // logic was replaced with exception.
    }
}

Here is me test code

@PrepareForTest(Util.class)
public class UtilTest extends PowerMockTestCase {

        @Test
        public void should_prevent_invoking_of_private_method_but_return_result_of_it() throws Exception {

            PowerMockito.mockStatic(Util.class);
            PowerMockito.when(Util.class, "anotherMethod").thenReturn("abc");

            String retrieved = Util.method();

            assertNotNull(retrieved);
            assertEquals(retrieved, "abc");
        }    
}

But every tile I run it I get this exception

java.lang.AssertionError: expected object to not be null

I suppose that I’m doing something wrong with mocking stuff. Any ideas how can I fix it?

Answer

To to this, you can use PowerMockito.spy(...) and PowerMockito.doReturn(...).

Moreover, you have to specify the PowerMock runner at your test class, and prepare the class for testing, as follows:

@PrepareForTest(Util.class)
@RunWith(PowerMockRunner.class)
public class UtilTest {

   @Test
   public void testMethod() throws Exception {
      PowerMockito.spy(Util.class);
      PowerMockito.doReturn("abc").when(Util.class, "anotherMethod");

      String retrieved = Util.method();

      Assert.assertNotNull(retrieved);
      Assert.assertEquals(retrieved, "abc");
   }
}

Hope it helps you.

Categories
discuss

Field or property cannot be found on object of type ‘org.springframework.beans.factory.config.BeanExpressionContext

The following bean definition:

<bean id="client" factory-bean="builder"
    factory-method="withConfiguration">
    <constructor-arg type="java.lang.String"
        value="#{ ${domain} == 'prod' ? 
                Base.${domain}.${realm}.rpt : Base.${domain}.${realm}}" />

fails with the following error:

org.springframework.web.context.ContextLoader: Context initialization failed { org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Field or property 'test' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext'

${domain} should evaluate to ‘test’. What is wrong with the configuration?

Answer

your property-placeholder result has to be wrapped to literal, if you are going to test it against another literal and don’t use it as a property as you in the rest of your expression:

value="#{ '${domain}' == 'prod' ? 
            'Base.${domain}.${realm}.rpt' : 'Base.${domain}.${realm}'}"

I’ve accepted your edit. Thanks.

The property-placeholder works before SpEL, so, any property-placeholder result becomes some SpEL part and it really has to be valid one.

I understand the first part '${domain}' == 'prod', when you really must have a literal for the PP result to compare it with another literal. The rest of your SpEL hasn’t been clear for me from the beginning, but now I see that it should be a String too for ctor arg.

Otherwise SpEL tries to treat test as some evaluation context property, that we see in the exception.

Try to imagine your SpEL without property-placeholders.

Categories
discuss

“Left join” of two different Java objects

I have a list of Object1 (List<Object1>) and a list of Object2 (List<Object2>)

  • Object 1 has multiple properties, including id
  • Object 2 has multiple properites, including object1id

I have some SQL background and what I’m trying to do is to perform a “left join” on

object1.id = object2.object1id

This would result in a List<Object3> that represents the left join. I could hardcode an algorithm in Java (for… for…), but I’m sure this wouldn’t be efficient with at least a complexity of n*m.

Do you have a better solution? (with code if possible, thanks!)

Answer

You are trying to do something that Java is not really meant for.

If you are able to do it, you would be better off adding an attribute to Object1, which would be a list of Object2 containing the objects related to this.

If you can’t, we still have the option of doing it naively, else you could try something like that:

HashSet<Integer> hs = new HashSet<Integer>(list2.size());
for(Object2 o : list2) {
    hs.add(o.object1id);
}
//hs contains all the ids of list2
List<Object1> result = new ArrayList<Object1>(); //Or another class implementing List
for(Object1 o : list1) {
    if(hs.contains(o.id))
        result.add(o);
}

Not pretty since you have to store all the ids in an HashSet, but since adding and accessing elements in HashSet are O(1) (theoretically), the algorithm is O(n+m)

If your Object3 class is constructed with an Object1 and Object2, use an HasMap instead of HashSet where the keys are ids, and the values object2. The last for loop in the code will become:

Object2 o2 = hs.get(o.id);
if(o2 != null)
    result.add(new Object3(o, o2);

Further to Óscar López comment:

If your objectid1 your not unique, you have to adapt the code as follows:

HashMap<Integer, List<Object2>> hm = new HashMap<Integer, List<Object2>>();
for(Object2 o : list2) {
    List<Object2> l = hm.get(o.objectid1);
    if(l != null) {
        l.add(o);
    } else {
        List<Object2> l = new ArrayList<Object2>();
        l.add(o);
        hm.put(o.objectid1, l);
}
//hm is map, where each entry contains the list of Object2 associated with objectid1
List<Object1> result = new ArrayList<Object1>();
for(Object1 o : list1) {
    List<Object2> l = hm.get(o.id);
    //l contains all Object2 with object1id = o.id
    for(Object2 o2 : l)
        result.add(new Object3(o, o2));
}

Still in O(n+m), but with bigger constants…

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..