A sorta extentsion on a method java - java

So i'm creating a API to java and i need a extention like thing on my method. Example:
someMethod().getName();
Something like that. Anyone know how?

What you are trying to do is something called method chaining. Let's put this example:
obj.methodOne().methodTwo()
This will call methodTwo() from the object returned by the call obj.methodOne(), so you can think the above chain as if it were this:
(obj.methodOne()).methodTwo()
Let's say you have this class:
public class MyClass2 {
public int methodTwo() {...}
}
Then, to be able to call methodTwo from the result of obj.methodOne(), the method methodOne() should return an instance of the class MyClass2:
public class MyClass1 {
public MyClass2 methodOne() {
return new MyClass2(); // returns instance of 'MyClass2'
}
}

Not sure what you mean, but this may help
class Foo {
Object someMethod() {
...
return new Object() {
public String toString() {
return "Bar";
}
}
}
}
What you're doing is returning an anonymous class and that overrides toString().
You can read more about anonymous classes here: http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html

I think you are unable to express your question.
1) If you want to have toString() method in a class you can do the following:
public class XYZ
{
//Your properties and methods
#Override
public String toString()
{
//Manipulate what you want to return as a String
return a_string;
}
}
2) You want to call a method on the result of a method. Method Chaining
class XYZ
{
//Your properties and methods
public ABC getABC()
{
return an_ABC_object;
}
}
class ABC
{
public void doSomething()
{
// do some work or print something
}
}
public class Test
{
public static void main(String arg[])
{
XYZ xyz=new XYZ();
xyz.getABC().doSomething();
}
}

Related

Invoking a method of an anonymous class without reflection in java

I want to do something like this
static <T> T mine()
{
return new Object(){void hello(){}};
}
so that I can do this
mine().hello();
the intend is to do something like this
mine.hello().hi().bye();
so either I declare classes each with 1 method hello,hi,bye and than return there instances or somehow I could return an anonymous class(with newly defined method) form each method like above. so that I dont have to write lot of classes.
Like it I can do
static <T> T tunnel(T t)
{
return t;
}
tunnel(new Object()
{
void hello()
{
System.out.println("hello");
}
}).hello();
but its of no use, I want to return anonymous object(created in tunnel itself) from tunnel , instead of returning passed argument
You probably want a fluent class. Something like
public class MyFluentClass {
public MyFluentClass methodOne() {
// do something
return this;
}
public MyFluentClass methodTwo() {
// do something
return this;
}
}
And then in your main method:
MyFluentClass myFuent = new MyFluentClass();
myFluent.methodOne().methodTwo();

Overload enum abstract method

Is it possible to overload Enum abstract method?
I have tried this in my code with no effect.
Presented class
public class Test {
public void test(String string){
System.out.println(string);
}
public void test(Object object){
System.out.println("Test1");
}
public static void main(String[] args) {
Object object = new Object();
test.test(object);
test.test("what if?");
}
}
gives expected result of
Test1
what if?
while enum
public enum TestEnum {
TEST1{
public void test(String string){
System.out.println(string);
}
public void test(Object object){
System.out.println("Test1");
}
},
TEST2{
public void test(Object object){
System.out.println("Test2");
}
};
public abstract void test(Object object);
}
public class Test {
public static void main(String[] args) {
Object object = new Object();
TestEnum.TEST1.test("what if?");
TestEnum.TEST1.test(object);
}
}
returns
Test1
Test1
Is it even possible to overload Enum methods or am I doing something wrong? Or maybe should I check for type inside of overriden method and then act accordingly? But then I remove switch statement only to introduce another switch statement.
The thing about enums is that values with bodies are implemented as anonymous subclasses of TestEnum; so they look like this:
final TestEnum TEST1 = new TestEnum() { /* body */ };
Whilst the concrete class of TEST1 is, say TestEnum$1 (or whatever name the compiler decides to give it), the reference is of type TestEnum, so any code outside the body of TEST1 can only access methods defined on TestEnum.
Yes is possible, you are somehow not implementing that in a particular way....
you should
define an interface with the methods you want to override
interface Ifoo {
public void test(Object object);
public void test(String object);
}
then remove the abstract method of the enum and make the enum implement that interface, but override those methods in every constant of the enumerator...
enum TestEnum implements Ifoo {
TEST1 {
#Override
public void test(String string) {
System.out.println(string);
}
#Override
public void test(Object object) {
System.out.println("Test1");
}
},
TEST2 {
#Override
public void test(Object object) {
System.out.println("Test2");
}
#Override
public void test(String string) {
System.out.println(string);
}
};
}
finally implement it like>
Object object = new Object();
TestEnum.TEST1.test("what if?");
TestEnum.TEST1.test(object);
TestEnum.TEST2.test("why not?");
TestEnum.TEST2.test(object);
your result should looks like:
what if?
Test1
why not?
Test2
You are showing an example with a class and then you are showing an example with an enum. I believe you think these examples are equivalent, however, they are completely different each other.
For the example of your class to be equivalent to the example of your enum, you should modify your Test class so that it extends an abstract AbstractTest class:
public abstract class AbstractTest {
public abstract void test(Object object);
}
public class Test extends AbstractTest {
public void test(String string) {
System.out.println(string);
}
#Override
public void test(Object object) {
System.out.println("Test1");
}
}
Now, if you try the same lines you've tried in your first main:
AbstractTest test = new Test();
Object object = new Object();
test.test(object);
test.test("what if?");
You'll notice that the output has now become:
Test1
Test1
Which is something to be expected, because Java doesn't provide a feature called dynamic dispatch. Informally, dynamic dispatch means that the overloaded method to be executed is decided at runtime, based on the polymorphic types of the parameters. Instead, Java decides the method to be executed at compilation time, based on the declared type of the object whose method is to be invoked (in this case AbstractTest).
With enums, this is exactly what happens. All the elements of the enum (TEST1 and TEST2 in your example) belong to the type of the enum (TestEnum in your case), so the compiler always goes for the method that is declared as abstract.
The reason why you get twice "Test1" is because you have declared only this method
public abstract void test(Object object);
Precisely, this method will "catch" all calls whit any type of parameter. String extends Object (indirectly), so String is Object and this method we be called.
In other words, method wich receives parameter String will be hidden by the method which receives parameter Object.
The solution is to add next method declaration in enum
public abstract void test(String string);
You will have to add the implementation of this method to TEST2 constant.
Code
public enum TestEnum {
TEST1 {
public void test(String string) {
System.out.println(string);
}
public void test(Object object) {
System.out.println("Test1");
}
},
TEST2 {
public void test(Object object) {
System.out.println("Test2");
}
#Override
public void test(String string) {
// TODO Auto-generated method stub
}
};
public abstract void test(Object object);
public abstract void test(String string);
}
This code gives output
what if?
Test1

Java method simulation

As part of behavioral testing I need to simulate the method call in a given class.
So say if I have a class like:
class A {
public void abc(){
new classB().getData();
}
public void xyz( boolean callabc){
if (callabc) {
abc();
}
}
So my requirement is to first find all methods in class A then find which method is making which call like xyz is calling abc which is calling class B getData method.
Is it possible to get all these data in Java?
You can transform your code into something like this:
public class A {
private final ClassB b;
public A(ClassB b) {
this.b = b;
}
public void abc(){
b.getData();
}
public void xyz( boolean callabc){
if (callabc) {
abc();
}
}
}
Then you can pass mock implementation of class B during tests. Then you can verify that some method was invoked on mock with specific parameters with mockito library:
http://static.javadoc.io/org.mockito/mockito-core/2.3.0/org/mockito/Mockito.html#1

Object class with anonymous type constructor

I am creating an Object as a class variable with anonymous type. There are no compilation errors. My question is how to use the class? How to call the methods that I am defining? Where is it used actually?
public class MyClass {
Object o = new Object(){
public void myMethod(){
System.out.println("In my method");
}
};
}
I am not able to call the myMethod() of object o. How to do that and when do we use this?
The only way to call a method of an anonymous class that is not part of the super class methods is to call it straight away:
new Object(){
public void myMethod(){
System.out.println("In my method");
}
}.myMethod();
If you just store the anonymous class in an Object variable you won't be able to call its method any more (as you have figured out).
However the usefulness of such a construct seems quite limited...
To do something like this, you should be having a method in Object class. This in short means you need to override the method defined in Object class.
Try something like:
Object o = new Object(){
public boolean equals(Object object){
System.out.println("In my method");
return this == object;//just bad example.
}
};
Object o2 = new Object();
System.out.println(o.equals(o2));will also print "In my method"
Your variable type is Object, so the only methods that the compiler will let you call are the ones declared in Object.
Declare a non-anonymous class instead:
private static class MyObject {
public void myMethod() {
System.out.println("In my method");
}
};
MyObject o = new MyObject();
You can use interfaces:
public interface MyInterface {
public void myMethod();
}
In your MyClass
public class MyClass {
MyInterface o = new MyInterface() {
#Override
public void myMethod() {
System.out.println("In my method");
}
};
public void doSomething() {
o.myMethod();
}
}

Super class which uses the values from children

I wanted to implement a method in a abstract class that is called by the inherited classes and uses their values.
For instance:
abstract class MyClass{
String value = "myClass";
void foo(){System.out.println(this.value);}
}
public class childClass{
String value="childClass";
void foo(){super.foo();}
}
public static void main(String[] args){
new childClass.foo();
}
This will output "myClass" but what I really want is to output "childClass". This is so I can implement a "general" method in a class that when extended by other classes it will use the values from those classes.
I could pass the values as function arguments but I wanted to know if it would be possible to implement the "architecture" I've described.
A super method called by the inherited class which uses the values from the caller not itself, this without passing the values by arguments.
You could do something like this:
abstract class MyClass {
protected String myValue() {
return "MyClass";
}
final void foo() {
System.out.println(myValue());
}
}
public class ChildClass extends MyClass {
#Override
protected String myValue() {
return "ChildClass";
}
}
and so on
This is a place where composition is better than inheritance
public class Doer{
private Doee doee;
public Doer(Doee doee){
this.doee = doee;
}
public void foo(){
System.out.println(doee.value);
}
}
public abstract class Doee{
public String value="myClass"
}
public ChildDoee extends Doee{
public String= "childClass"
}
...
//Excerpt from factory
new Doer(new ChildDoee);
I believe you are asking whether this is possible:
public class MyClass {
void foo() {
if (this instanceof childClass) // do stuff for childClass
else if (this intanceof anotherChildClass) // do stuff for that one
}
}
So the answer is "yes, it's doable", but very much advised against as it a) tries to reimplement polymorphism instead of using it and b) violates the separation between abstract and concrete classes.
You simply want value in MyClass to be different for an instance of childClass.
To do this, change the value in the childClass constructor:
public class childClass {
public childClass() {
value = "childClass";
}
}
Edited:
If you can't override/replace the constructor(s), add an instance block (which gets executed after the constructor, even an undeclared "default" constructor):
public class childClass {
{
value = "childClass";
}
}

Categories