Java send class parameters by only one object - java

It is possible to create an Object as "only for parameters"?. For example:
class MyClass {
public String a;
public Number b;
public MyClass(Object params) {
this.a = params.a !== null ? params.a : "default";
this.b = params.b !== null ? params.b : 0;
}
}
void main() {
MyClass myclass1 = new MyClass(new Object() {
String a = "hey";
});
MyClass myclass2 = new MyClass(new Object() {
Number b = 123;
});
MyClass myclass3 = new MyClass(new Object() {
String a = "!!!";
Number b = 5;
});
}
Obviously this code doesn't work, I tried a lot of ways trying to replicate it, maybe with Templates (Generic)?
The expected results will be:
myclass1.a == "hey";
myclass1.b == 0;
myclass2.a == "default";
myclass2.b == 123;
myclass3.a == "!!!";
myclass3.b == 5;

You could use a Builder pattern to create required instance:
public final class MyClass {
private final String str;
private final Number number;
public static Builder builder() {
return new Builder();
}
private MyClass(Builder builder) {
str = builder.str;
number = builder.number;
}
public String getStr() {
return str;
}
public Number getNumber() {
return number;
}
public static final class Builder {
private String str = "default";
private Number number = 0;
private Builder() {
}
public MyClass build() {
return new MyClass(this);
}
public Builder str(String str) {
this.str = str;
return this;
}
public Builder number(Number number) {
this.number = number;
return this;
}
}
}
Demo:
public static void main(String... args) {
MyClass myclass1 = MyClass.builder().str("hey").build();
MyClass myclass2 = MyClass.builder().number(123).build();
MyClass myclass3 = MyClass.builder().str("!!!").number(5).build();
}
In case you do not want to use Builder pattern, you could use class override:
public class MyClass {
public String getStr() {
return "default";
}
public Number getNumber() {
return 0;
}
}
public static void main(String... args) throws IOException {
MyClass myclass1 = new MyClass() {
#Override
public String getStr() {
return "hey";
}
};
MyClass myclass2 = new MyClass() {
#Override
public String getStr() {
return "hey";
}
#Override
public Number getNumber() {
return 123;
}
};
MyClass myclass3 = new MyClass() {
#Override
public String getStr() {
return "!!!";
}
#Override
public Number getNumber() {
return 5;
}
};
}

Related

Class for easy generation of xpaths

I would like to write a class for generating xpaths. The class should have 2 methods: down(String string) and child(String string).
I would like to use the class like that:
XpathBuilder.child("div").down("button").child("a").child("span")
//That should return a String: div//button/a/span
Could anybody suggest me how can I do that?
You could take a look at builder pattern.
Here is one example (uses internal builder class):
public class XpathBuilder {
public Builder builder() {
return new XpathBuilder.Builder();
}
class Builder {
private final StringBuilder sb;
Builder() {
sb = new StringBuilder();
}
public Builder child(String name) {
sb.append("/").append(name);
return this;
}
public Builder down(String name) {
sb.append("//").append(name);
return this;
}
public String build() {
return sb.toString();
}
}
}
It can be called like this:
String path = new XpathBuilder().builder().child("div").down("button").child("a").child("span").build();
Here is another example (uses builder as well as singleton pattern):
public class XpathBuilder {
private final StringBuilder sb;
private static XpathBuilder instance;
private XpathBuilder() {
sb = new StringBuilder();
}
public static XpathBuilder newInstance() {
if (instance == null) {
instance = new XpathBuilder();
}
return instance;
}
public XpathBuilder child(String name) {
sb.append("/").append(name);
return this;
}
public XpathBuilder down(String name) {
sb.append("//").append(name);
return this;
}
public String build() {
return sb.toString();
}
}
It can be called like this:
String path = XpathBuilder.newInstance().child("div").down("button").child("a").child("span").build();
I think I found an easier solution overriding the toString method from the class Object. Doing that I need only one class:
public class XpathBuilder {
StringBuilder sb = new StringBuilder();
public XpathBuilder child(String string) {
sb.append("/"+string);
return this;
}
public XpathBuilder down(String string){
sb.append("//"+string);
return this;
}
#Override
public String toString(){
return sb.toString();
}

Pass object of any type to class B

I want to be able to pass Object from any class to a specific class. How do i do this? I pass the object in the constructor of the receiving class. One workaround i know is using static variables, but i need the whole object not just the variables.
public class tryitout
{
public static void main(String[] args) {
A a = new A();
B b = new B(a);
b.print();
}
}
class A implements Serializable
{
public int a;
public String b;
A()
{
this.a = 12;
this.b =" nach";
}
}
class B
{
Object obj;
B(Object o)
{
obj = o;
}
void print()
{
System.out.println(obj.a + " "+ obj.b);
}
}
Using Generics :
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
public class tryitout {
public static void main(String[] args) {
ClassA a = new ClassA("sap",11);
ClassB<ClassA> b = new ClassB<ClassA>(a);
b.print();
}
}
public class ClassA {
private String name;
private int id;
public ClassA(String name, int id) {
super();
this.name = name;
this.id = id;
}
#Override
public String toString() {
return "ClassA [name=" + name + ", id=" + id + "]";
}
}
public class ClassB<T> {
private T genericObj;
public ClassB(T genericObj){
this.genericObj = genericObj;
}
public void print() {
Field nameField = getField("name");
Field idField = getField("id");
try {
System.out.println(nameField.get(genericObj));
System.out.println(idField.getInt(genericObj));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
private Field getField(String FieldName) {
Field fld = null;
try {
fld = genericObj.getClass().getDeclaredField(FieldName);
if(Modifier.isPrivate(fld.getModifiers())) {
fld.setAccessible(true);//To get access over private fields
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
return fld;
}
}
using generics you can access method also.
I don't know your exact purpose,otherwise other classes can extend any particular Abstract class and you can use that Abstract class as a type inside classB.
public class TypeClass {
protected String name;
protected int id;
protected void paint(){
System.out.println("name: " + name + " | id: " + id);
}
}
public class ClassC extends TypeClass{
public ClassC(String name, int id) {
super();
this.name = name;
this.id = id;
}
#Override
public String toString() {
return "ClassA [name=" + name + ", id=" + id + "]";
}
}
package javaConcept.generics;
public class ClassD {
private TypeClass typeClass;
public ClassD(TypeClass typeClass) {
this.typeClass = typeClass;
}
public void newPaint() {
typeClass.paint();
}
}
public class TempoClass {
public static void main(String[] args) {
ClassC c = new ClassC("sap",11);
ClassD b = new ClassD(c);
b.newPaint();
}
}
maybe use static blocks and anonymous blocks some thing like this
public class HelloWorld{
public static void main(String []args){
B ob1= new B();
C ob2= new C(B.ob);
D ob3= new D();
C ob4= new C(ob3.ob);
}
}
class A
{
//this is empty class just for sake of object to be created
public void imWorking()
{
System.out.println("test");
}
}
class B
{
public static A ob;
static{ob=new A();}//static called once class gets loaded
}
class C
{
public C(){}//Default constructor
public C(A a){a.imWorking();}
}
class D
{
public A ob;
{ob=new A();}//ananomous block calls everytime a new object is created
}
more info Static Initialization Blocks blocks & anonymous blocks][1]

Why is the TestRestTemplate postForEntity object body null

So my problem is this essentially:
http://i.imgur.com/rE0z7Um.png
Here is the class that throws the error once the response is called in the #Test method:
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#ComponentScan
#Import(RepositoryRestMvcAutoConfiguration.class)
public class AjaxControllerTest {
static final String DEFAULT_URI = "/api/some_function";
SomeObjects someObjects;
#Autowired
private TestRestTemplate restTemplate;
#Before
public void setUp() {
SortedSet<SomeObject> someObjectsSet = new TreeSet<>();
someObjectsSet.add(new SomeObject());
someObjectsSet.add(new SomeObject());
someObjects = new SomeObjects(someObjectsSet);
}
#Test
public void testGetFullJsonSuccessful() {
ResponseEntity<SomeObjects> response = this.restTemplate.postForEntity(DEFAULT_URI, someObjects, SomeObjects.class);
assertThat(response).isNotNull();
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED);
assertThat(response.getBody()).isNotNull();
}
}
Here is the AjaxController class function:
#PostMapping(value = "/api/some_function", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> someFunction(#RequestBody SomeObjects someObjects, Errors errors) {
AjaxResponseBody result = new AjaxResponseBody();
if (errors.hasErrors()) {
result.setMsg(errors.getAllErrors().stream().map(x -> x.getDefaultMessage()).collect(Collectors.joining(";")));
return ResponseEntity.badRequest().body(result);
}
Set<SomeObject> someObjectsSet = new TreeSet<>();
if (someObjectsSet.isEmpty()) {
result.setMsg("No data found.");
} else {
result.setMsg("Success");
}
result.setResult(someObjectsSet);
return ResponseEntity.ok(result);
}
Ajax Response object:
public class AjaxResponseBody {
private String msg;
private Set<SomeObject> result;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Set<SomeObject> getResult() {
return result;
}
public void setResult(Set<SomeObject> result) {
this.result = result;
}
}
and Involved POJOs:
public class SomeObject implements Comparable<SomeObject> {
private String str;
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SomeObject that = (SomeObject) o;
return str != null ? str.equals(that.str) : that.str == null;
}
#Override
public int hashCode() {
return str != null ? str.hashCode() : 0;
}
#Override
public int compareTo(SomeObject o) {
return 0;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
}
public class SomeObjects {
private SortedSet<SomeObject> someObjects;
public SomeObjects(SortedSet<SomeObject> someObjects) {
this.setSomeObjects(someObjects);
}
public SomeObjects() {
}
public SortedSet<SomeObject> getSomeObjects() {
return someObjects;
}
public void setSomeObjects(SortedSet<SomeObject> someObjects) {
this.someObjects = someObjects;
}
}
Sorry for the code spam, but I want to be complete and I can't trace the problem myself. If I get an answer I will edit and trim down the unimportant code.

How to refactor a class with multiple Lists + getters and setters for each list

I have the following class:
public class RefactorMe {
private static List<Event<Apple>> mAppleEventList = new ArrayList<Event<Apple>>();
private static List<Event<Banana>> mBananaEventList = new ArrayList<Event<Banana>>();
private static List<Event<Orange>> mOrangeEventList = new ArrayList<Event<Orange>>();
public static List<Event<Apple>> getAppleList() {
return mAppleEventList;
}
public static List<Event<Banana>> getBananaEventList() {
return mBananaEventList;
}
public static List<Event<Orange> getOrangeList() {
return mOrangeEventList;
}
public static void addAppleEvent(Event<Apple> pEvent) {
mAppleEventList.add(pEvent);
}
public static void addBananaEvent(Event<Banana> pEvent) {
mBananaEventList.add(pEvent);
}
public static void addOrangeEvent(Event<Orange> pEvent) {
mOrangeEventList.add(pEvent);
}
}
I tried refactoring it using the Visitor pattern but could not get it to work because of the generics.. Is there a better way to do this?
Following on #user902383 by using the Map here is a solution for you in Java 7:
public class RefactorMe {
class Event<K> {
public K getNewObject() {
return null;
}
}
private static Map<Class<?>, List<Event<?>>> eventLists = new HashMap<>();
public static <E> List<Event<E>> getEventList(Class<E> clazz) {
return (List) eventLists.get(clazz);
}
public static <E extends Event<E>> void addEvent(Event<E> pEvent) {
Class<E> key = (Class<E>) pEvent.getNewObject().getClass();
List<Event<?>> events = eventLists.get(key);
if (events == null) {
events = new ArrayList<>();
eventLists.put(key, events);
}
events.add(pEvent);
}
}

JUnit test of the same object

I want to make a unit test suite of the same object with same variable but different values. However if the object get the same name (created by this.setName("testlaunch"); (we must have the name of a method tested by JUnit), it runs only one test.
If i don't write this.setName("testlaunch"); it complains saying junit.framework.AssertionFailedError: TestCase.fName cannot be null.
I don't know what to do...
public class LanceurRegleGestion extends TestSuite
{
public static Test suite()
{
Class maClasse = null;
TestSuite suite = new TestSuite();
String filtre = ".*.xml";
// on compile le pattern pour l'expression réguliere
Pattern p = Pattern.compile(filtre);
String path = "D:/Documents/workspace/Solipsisme/src/ReglesGestion/XML/";
// on liste les fichiers du repertoire
String [] u = new File(path).list();
// on parcours la liste de fichier
System.out.println("Initialisation");
for (int i=0; i
et le code de l'objet serialisé
public class Application extends TestCase {
private String nomappli;
private String id2_1;
private String id3_1;
private String id4_1;
private String id2_2;
private String id3_2;
private String id4_2;
private String id5_2;
private String id6_2;
private String id7_2;
private String id8_2;
private String id9_2;
private String id2_3;
private String id3_3;
private String id4_3;
private String id2_4;
private String id3_4;
private String id4_4;
private String id2_5;
private String id3_5;
private String id4_5;
private String id5_5;
private String id6_5;
private String id7_5;
private static Selenium selenium;
public Application(String nomappli,String id2_1,String id3_1,String id4_1,String id2_2,String id3_2,String id4_2,String id5_2,String id6_2,String id7_2,String id8_2,String id9_2,String id2_3,String id3_3,String id4_3,String id2_4,String id3_4,String id4_4,String id2_5, String id3_5,String id4_5,String id5_5,String id6_5,String id7_5)
{
this.setName("testlaunch");
this.nomappli = nomappli;
this.id2_1 = id2_1;
this.id3_1 = id3_1;
this.id4_1 = id4_1;
this.id2_2 = id2_2;
this.id3_2 = id3_2;
this.id4_2 = id4_2;
this.id5_2 = id5_2;
this.id6_2 = id6_2;
this.id7_2 = id7_2;
this.id8_2 = id8_2;
this.id9_2 = id9_2;
this.id2_3 = id2_3;
this.id3_3 = id3_3;
this.id4_3 = id4_3;
this.id2_4 = id2_4;
this.id3_4 = id3_4;
this.id4_4 = id4_4;
this.id2_5 = id2_5;
this.id3_5 = id3_5;
this.id4_5 = id4_5;
this.id5_5 = id5_5;
this.id6_5 = id6_5;
this.id7_5 = id7_5;
}
public Application(){
}
public String toString()
{
return getNomappli();
}
public void setNomappli(String nomappli)
{
this.nomappli = nomappli;
}
public String getNomappli()
{
return this.nomappli;
}
public void setId2_1(String id2_1)
{
this.id2_1 = id2_1;
}
public String getId2_1()
{
return this.id2_1;
}
public void setId3_1(String id3_1)
{
this.id3_1 = id3_1;
}
public String getId3_1()
{
return this.id3_1;
}
public void setId4_1(String id4_1)
{
this.id4_1 = id4_1;
}
public String getId4_1()
{
return this.id4_1;
}
public void setId2_2(String id2_2)
{
this.id2_2 = id2_2;
}
public String getId2_2()
{
return this.id2_2;
}
public void setId3_2(String id3_2)
{
this.id3_2 = id3_2;
}
public String getId3_2()
{
return this.id3_2;
}
public void setId4_2(String id4_2)
{
this.id4_2 = id4_2;
}
public String getId4_2()
{
return this.id4_2;
}
public void setId5_2(String id5_2)
{
this.id5_2 = id5_2;
}
public String getId5_2()
{
return this.id5_2;
}
public void setId6_2(String id6_2)
{
this.id6_2 = id6_2;
}
public String getId6_2()
{
return this.id6_2;
}
public void setId7_2(String id7_2)
{
this.id7_2 = id7_2;
}
public String getId7_2()
{
return this.id7_2;
}
public void setId8_2(String id8_2)
{
this.id8_2 = id8_2;
}
public String getId8_2()
{
return this.id8_2;
}
public void setId9_2(String id9_2)
{
this.id9_2 = id9_2;
}
public String getId9_2()
{
return this.id9_2;
}
public void setId2_3(String id2_3)
{
this.id2_3 = id2_3;
}
public String getId2_3()
{
return this.id2_3;
}
public void setId3_3(String id3_3)
{
this.id3_3 = id3_3;
}
public String getId3_3()
{
return this.id3_3;
}
public void setId4_3(String id4_3)
{
this.id4_3 = id4_3;
}
public String getId4_3()
{
return this.id4_3;
}
public void setId2_4(String id2_4)
{
this.id2_4 = id2_4;
}
public String getId2_4()
{
return this.id2_4;
}
public void setId3_4(String id3_4)
{
this.id3_4 = id3_4;
}
public String getId3_4()
{
return this.id3_4;
}
public void setId4_4(String id4_4)
{
this.id4_4 = id4_4;
}
public String getId4_4()
{
return this.id4_4;
}
public void setId2_5(String id2_5)
{
this.id2_5 = id2_5;
}
public String getId2_5()
{
return this.id2_5;
}
public void setId3_5( String id3_5)
{
this.id3_5 = id3_5;
}
public String getId3_5()
{
return this.id3_5;
}
public void setId4_5(String id4_5)
{
this.id4_5 = id4_5;
}
public String getId4_5()
{
return this.id4_5;
}
public void setId5_5(String id5_5)
{
this.id5_5 = id5_5;
}
public String getId5_5()
{
return this.id5_5;
}
public void setId6_5(String id6_5)
{
this.id6_5 = id6_5;
}
public String getId6_5()
{
return this.id6_5;
}
public void setId7_5(String id7_5)
{
this.id7_5 = id7_5;
}
public String getId7_5()
{
return this.id7_5;
}
public void setSelenium(Selenium selenium)
{
this.selenium = selenium;
}
public Selenium getSelenium()
{
return this.selenium;
}
public final static void login()
{
selenium.open("apj/ident");
selenium.type("username", "hsuzumiya-cp");
selenium.type("password", "1");
selenium.click("enterButton");
selenium.waitForPageToLoad("9999999");
}
public void testlaunch()
{
generique(this.nomappli,this.id2_1,this.id3_1,this.id4_1,this.id2_2,this.id3_2,this.id4_2,this.id5_2,this.id6_2,this.id7_2,this.id8_2,this.id9_2,this.id2_3,this.id3_3,this.id4_3,this.id2_4,this.id3_4,this.id4_4,this.id2_5,this.id3_5,this.id4_5,this.id5_5,this.id6_5,this.id7_5);
}
public void setUp() throws Exception
{
System.out.println("Initialisation");
selenium = new DefaultSelenium("127.0.0.1",4444,"*iexplore", "http://hsuzumiya/");
selenium.start();
selenium.setTimeout("90000");
selenium.setSpeed("500");
login();
}
public void generique(String nomappli,String id2_1,String id3_1,String id4_1,String id2_2,String id3_2,String id4_2,
String id5_2,String id6_2,String id7_2,String id8_2,String id9_2,String id2_3,String id3_3,String id4_3,String id2_4,
String id3_4,String id4_4,String id2_5, String id3_5,String id4_5,String id5_5,String id6_5,String id7_5
)
{
System.out.println(nomappli);
selenium.click("valider");
selenium.waitForPageToLoad("30000");
selenium.click("validertout");
}
public final void tearDown() throws Exception
{
System.out.println("Killing session");
selenium.stop();
}
}
Being new to junit, I stumbled upon this question hoping to solve a problem I had getting the same message. Through further research, I found that it is necessary to pass the name of the test function you want to invoke through addTest to the constructor of the test case class. A simple (and useless, other than illustration) example follows:
JunitTestCases.java
import junit.framework.TestCase;
public class JunitTestCases extends TestCase {
public JunitTestCases(String fnName) {
super(fnName);
}
public void testA() {
assertTrue("assertTrue failed", true);
}
}
JunitTestSuite.java:
import junit.framework.*;
public class JunitTestSuite {
public static Test suite() {
TestSuite suite = new TestSuite();
suite.addTest(new JunitTestCases("testA"));
return suite;
}
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
}
When I compiled with:
javac -cp .:path/to/junit-X.X.X.jar JunitTestSuite.java
and ran with
java -cp .:path/to/junit-X.X.X.jar JunitTestSuite
this worked with no errors, with junit giving me an OK message.

Categories

Resources