I have the following class structure. I would like to know how can I jump in eclipse to the actual implementation of th gethod printVar().
If I hover (hold down STRG) over the 2 method calls in main and click open implementation I get both Classes displayed. Is there a way to directly jump to the implementation in class B for this method call w.getWrapperVar().printVar()
public class A {
private String var;
public A(String a){
this.var=a;
}
public void printVar(){
System.out.println("class A print: " + this.var);
}
}
public class B extends A{
private String var;
public B(String a){
super(a);
this.var=a;
}
#Override
public void printVar(){
System.out.println("class B print: " + this.var);
}
}
public class Wrapper {
private B wrapperVar;
private A wrapperVar2;
public Wrapper(String var){
this.wrapperVar = new B(var);
this.wrapperVar2 = new A(var);
}
// explicit Return Class A
public A getWrapperVar(){
return this.wrapperVar;
}
public A getWrapperVar2(){
return this.wrapperVar2;
}
}
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Wrapper w = new Wrapper("value");
w.getWrapperVar().printVar();
w.getWrapperVar2().printVar();
}
}
Eclipse doesn't know that the implementation class is B, so it can't take you directly to B.
However, you can click on printVar and press Ctrl-G to search for all methods that might be the actual implementation.
After selecting a method call you can hit the F3 function key. This action will take you to the definition of the method. This definition may be in an interface.
When you are in that file you may want to hit Ctrl+T. This will bring up a type hierarchy showing the classes that implement the method you were looking for.
Hope this helps.
Related
I would like to be able to provide a functional interface that accepts several different types of lambda functions.
I read this. The first answer to this question clarifies why overloading an abstract method in a functional interface could cause undefined behavior. However, is there a way to do the equivalent of overloading an abstract method in a functional interface if I supply all of the defaults?
I would like to be able to write something like the following code:
Ball b = () -> System.out.println("You hit it!");
Ball ba = (boolean miss) -> System.out.println(miss);
b.hit();
b.hit(false);
ba.hit();
ba.hit(false);
The desired result would be:
You hit it!
default false
default hit
false
Consider the following (non-compilable) code (mostly copied from the linked question):
#FunctionalInterface
public interface Ball
{
void hit();
void hit(boolean miss);
default void hit(){
System.out.println("default hit");
}
default void hit(boolean miss){
System.out.println("default" + miss);
}
}
I am looking for an alternative to this code that would compile.
You could wrap the interface in a class and then pass on the method calls to the interfaces internally.
Example code:
public class Test{
public static void main(String... args) throws Exception{
Ball b = new Ball(() -> System.out.println("You hit it!"));
Ball ba = new Ball((boolean miss) -> System.out.println(miss));
b.hit();
b.hit(false);
ba.hit();
ba.hit(false);
}
public static class Ball{
final Hit a;
final HitBoolean b;
public Ball(Hit a){
this.a = a;
b = (miss) -> System.out.println("default " + miss);
}
public Ball(HitBoolean b){
this.b = b;
a = () -> System.out.println("default hit");
}
public void hit(){
a.hit();
}
public void hit(boolean miss){
b.hit(miss);
}
}
public interface Hit{
void hit();
}
public interface HitBoolean{
void hit(boolean miss);
}
}
Output of the program:
You hit it!
default false
default hit
false
You could do something like this. But you would need to name your variables properly to keep track of both the arg and the consumer that takes it.
#FunctionalInterface
interface Ball<T> {
void hit();
static <T> Ball<T> withArg(T arg, Consumer<T> com) {
return () -> com.accept(arg);
}
}
public class Demo {
public static void main(String[] args) {
Ball<Boolean> b = () -> System.out.println("You Hit it!");
b.hit();
Ball<Boolean> ba = Ball.withArg(false, a -> System.out.println(a));
Ball<Boolean> bb = Ball.withArg(true, a -> System.out.println(a));
ba.hit();
bb.hit();
}
}
first thing about functional interface is , it can have only one abstract method.In that case you cant even think of the second method (let it be abstract method too). you can have any number of default methods.
So answer is 100% not possible and Your code above will get compilation error as you kept #FunctionalInterface annotation which strictly prohibits keeping more than one abstract method.
As per your code
#FunctionalInterface
public interface MyInter {
public abstract void fly();
public abstract void fly(int a);
default void fly() {} \\line1
default void fly(int g) { } \\line2
}
line 1 and 2 will throw compile time error as java sees them by method name are same and argument types are same , they will never bother of return type or default or etc..(primary rule of overloading).
more over if remove line 1 and 2 , then too code will throw error because #functionalinterface will give compilation error stating invalid '#FunctionalInterface' annotation; MyInter is not a functional interface .
Hope this answers your question...
I am writing a testing framework using Gauge.
I want some initilization logic performed in one class, and the steps logic to reuse it, like this:
public class A {
protected String property = "";
#BeforeSpec
public void init(){
property = "hello";
}
}
public class B extends A {
#Step("...")
public void verifyProperty() {
assertEquals(property, "hello");
}
}
I can't seem to be able to achieve this. When performing the steps, the "property" is always null.
Placing the #BeforeSpec in class B and calling super.init() works, but I would like to avoid having this call in every test class that extends A.
Has anyone encountered and solved such an issue?
Try to use a static variable:
public class A {
public static String property = "";
#BeforeSpec
public void init(){
property = "hello";
}
}
public class B {
#Step("...")
public void verifyProperty() {
assertEquals(A.property, "hello");
}
}
I'm building an android app (but this is not important for the post) and I'm writing a method called scrollUntilSelectedAvatar() that contain a class:
public class AvatarManager {
private HorizontalScrollView avatarPageHorizontalScrollView;
//mehod that contains the inner class
public void scrollUntilSelectedAvatar(HorizontalScrollView avatarPageHorizontalScrollView){
this.avatarPageHorizontalScrollView = avatarPageHorizontalScrollView;
avatarPageHorizontalScrollView.post(new Runnable() {
#Override
public void run() {
AvatarManager.this.avatarPageHorizontalScrollView.scrollTo(100, 0);
}
});
}
}
My question is: what's the correct way to access avatarPageHorizontalScrollView (that I pass to the method as an argument) inside the inner class new Runnable().
The way I found (AvatarManager.this.avatarPageHorizontalScrollView) doesn't seems the best way.
Thank everybody for the help :)
The way you did it - is the one and only correct. Syntax of some thing about inner classes may seem quite strange. But it is just like it is.
public class A {
private int a;
private abstract class B {
public abstract void printA();
}
public B makeB() {
return new B() {
#Override
public void printA() {
System.out.println(A.this.a);
}
};
}
}
Is there a way to always execute a function before any other function of a class is called?
I have a class where I need to refresh some fields always before any function is called:
public class Example {
private int data;
public void function1(){
}
public void function2(){
}
//#BeforeOtherFunction
private void refresh(){
// refresh data
}
}
Because it seems to be bad programming, I don't want to call refresh at the beginning of every other function. Since other persons are going to work on this project as well, there would be the danger, that somebody extends the calls and doesn't call refresh.
JUnit has a solution for this with the #Before-Annotation. Is there a way to do this in other classes as well?
And by the way: If you know a programming pattern wich solves this problem in another way than executing a function everytime any function is called, that would be very helpful, too!
Use a dynamic proxy in which you can filter to those methods before which your specific "before" method should be called. And call it in those cases before dispatching the call. Please see the answer from How do I intercept a method invocation with standard java features (no AspectJ etc)?
UPDATE:
An interface is needed to be separated for the proxy. The refresh() method cannot remain private. It must be public and part of the interface (which is not nice here) to be able to be called from the proxy.
package CallBefore;
public interface ExampleInterface {
void function1();
void function2();
void otherFunction();
void refresh();
}
Your class implements that interface:
package CallBefore;
public class Example implements ExampleInterface {
#Override
public void function1() {
System.out.println("function1() has been called");
}
#Override
public void function2() {
System.out.println("function2() has been called");
}
#Override
public void otherFunction() {
System.out.println("otherFunction() has been called");
}
#Override
public void refresh() {
System.out.println("refresh() has been called");
}
}
The proxy which does the trick. It filters the needed methods and calls refresh().
package CallBefore;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ExampleProxy implements InvocationHandler {
private ExampleInterface obj;
public static ExampleInterface newInstance(ExampleInterface obj) {
return (ExampleInterface) java.lang.reflect.Proxy.newProxyInstance(obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(), new ExampleProxy(obj));
}
private ExampleProxy(ExampleInterface obj) {
this.obj = obj;
}
#Override
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
Object result;
try {
if (m.getName().startsWith("function")) {
obj.refresh();
}
result = m.invoke(obj, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
} catch (Exception e) {
throw new RuntimeException("unexpected invocation exception: " + e.getMessage());
}
return result;
}
}
The usage:
package CallBefore;
public class Main {
public static void main(String[] args) {
ExampleInterface proxy = ExampleProxy.newInstance(new Example());
proxy.function1();
proxy.function2();
proxy.otherFunction();
proxy.refresh();
}
}
Output:
refresh() has been called
function1() has been called
refresh() has been called
function2() has been called
otherFunction() has been called
refresh() has been called
This may not solve your exact problem but at least could be a starting point if you are allowed considering a re-design. Below is a simple implementation but with some small touches I believe you can achieve a more elegant solution. BTW, this is called Dynamic Proxy Pattern.
First thing you need is an interface for your class.
public interface Interface {
void hello(String name);
void bye(String name);
}
public class Implementation implements Interface {
#Override
public void hello(String name) {
System.out.println("Hello " + name);
}
#Override
public void bye(String name) {
System.out.println("Bye " + name);
}
}
Then java.lang.reflect.Proxy class comes to help. This class is able to create an instance for a given interface at runtime. It also accepts an InvocationHandler which helps you to capture method calls and looks like this.
public class InvocationHandlerImpl implements InvocationHandler {
private final Object instance;
public InvocationHandlerImpl(Object instance) {
this.instance = instance;
}
#Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result;
try {
System.out.println("Before");
result = method.invoke(instance, args);
System.out.println("After");
} catch (Exception e){
e.printStackTrace();
throw e;
} finally {
System.out.println("finally");
}
return result;
}
}
After all your client code will look like this.
Interface instance = new Implementation();
Interface proxy = (Interface)Proxy.newProxyInstance(
Interface.class.getClassLoader(),
new Class[] { Interface.class },
new InvocationHandlerImpl(instance));
proxy.hello("Mehmet");
proxy.bye("Mehmet");
Output for this code is
Before
Hello Mehmet
After
finally
Before
Bye Mehmet
After
finally
I would define getters for every field and do the refreshment inside the getter. If you want to avoid unrefreshed access to your private fields at all, put them in a superclass (together with the getters which call refresh).
Depending on your project structure, it may be also sensible to introduce a separate class for all data that is regularly refreshed. It can offer getters and avoid that anyone accesses the non-refreshed fields.
Not in Java SE, but if you are using Java EE, you could use interceptors.
For standalone applications, you could consider using a bytecode manipulation framework, like javassist.
You can have a protected getter method for data. Access getData method instead of using data field. Child classes will see only getData and will have updated data every time.
public class Example {
private int data;
public void function1(){
}
public void function2(){
}
protected int getData(){
refresh();
return data;
}
//#BeforeOtherFunction
private void refresh(){
// refresh data
}
}
It is better to write another method which will be made protected(accessible to the child classes) which will call first the refresh method and then call the function.
This way the data would be refreshed before the function is called everytime(As per your requirement).
eg:
protected void callFunction1(){
refresh();
function();
}
Thanks,
Rajesh
You should use Decorator in this case. Decorator is a good choice for something like interceptor. Example here: https://msdn.microsoft.com/en-us/library/dn178467(v=pandp.30).aspx
I have two classes:
public jComboBox() {
... // this is a autocomplete jComboBox btw
...
combo.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie) {
if(ie.getStateChange() == 1) {
String selectedItem = (String)getSelectedItem();
randomMethod(selectedItem);
}
}
});
}
private void randomMethod(String selectedItem){
someClass sc = new someClass();
String randomString = selectedItem;
sc.getRandomString(randomString);
}
and
public someClass() {
...
...
}
public void getRandomString(String randomString){
defaultTableModel.setRowCount(0);
.. do-something ..
}
Is this method fine? If not, I need some alternative on this one, because i'm having problems for example, using defaultTableModel.setRowCount(0) because the table wont empty, not unless I put the setRowCount(0) on other methods inside someClass class.
Basic java access specifier stuff..... how are you calling this private method getRandomString from randomMethod()? the visibility of private method of a class is only the class, not anywhere else. Therefore, your following code:
private void randomMethod(String selectedItem){
someClass sc = new someClass();
String randomString = selectedItem;
fs.getRandomString(randomString); // This will not work
}
is not going to work because of the access specifier private. If you can allow the access rights to be specific to the package you have, you can change it to:
protected void getRandromString(String randromString) {...}
Just to demonstrate what I mean:
package com.stackoverflow.solutionmaker;
public class Aclass {
public Aclass(){
somePrivMethod();
}
public void aMethod(){
System.out.println("Can see me from anywehre bcoz I am public");
}
private void somePrivMethod(){
System.out.println("Cannot find me from anywhere because I am private t Aclass");
}
}
Now the runner class:
package com.stackoverflow.solutionmaker;
public class StackOverflowSolutionsRunner {
public static void main(String[] args) {
Aclass aClass = new Aclass(); // It will display"Cannot find me from anywhere because I am private t Aclass"
aClass.aMethod(); // It will display "Can see me from anywehre bcoz I am public
aClass.somePrivMethod(); // Will throw a compile-time error
}
}
A good exercise for you now to compile these two from command line and see what error message you get. Alternatively, using Eclipse smart IDE or Jcreator, you can see that your private access specifier is causing red messages to appear.