This is my code.
public class SubFunction {
private String drawTribleX(){
return trible("X");
}
private String trible(String t){
return t + t + t;
}
public static void main(String[] args){
SubFunction o = new SubFunction();
System.out.println(o.drawTribleX());
}
}
Can I do something like this ?
public class SubFunction {
private String drawTribleX(){
// *** move trible(t) inside drawTribleX() ***
private String trible(String t){
return t + t + t;
}
return trible("X");
}
public static void main(String[] args){
SubFunction o = new SubFunction();
System.out.println(o.drawTribleX());
}
}
Thank you.
Update 2014-02-09:
JDK 8 introduced lambdas (anonymous function expressions) which allow you to solve it like this:
Function<String, String> trible = s -> s+s+s;
System.out.println(trible.apply("X")); // prints XXX
(JDK 7 and below)
No, Java does not support "directly" nested methods. (Most functional languages do though, including some JVM languages such as Scala and Clojure!)
Just for reference though; You can define local classes (classes within methods) so this does compile
class SubFunction {
private String drawTribleX(){
// *** move trible(t) inside drawTribleX() ***
class Trible {
private String trible(String t){
return t + t + t;
}
}
return new Trible().trible("X");
}
public static void main(String[] args){
SubFunction o = new SubFunction();
System.out.println(o.drawTribleX());
}
}
Note though that there are some restrictions on local classes
3.11.2. Restrictions on Local Classes
Local classes are subject to the following restrictions:
A local class is visible only within the block that defines it; it can never be used outside that block.
Local classes cannot be declared public, protected, private, or static. These modifiers are for members of classes; they are not allowed with local variable declarations or local class declarations.
Like member classes, and for the same reasons, local classes cannot contain static fields, methods, or classes. The only exception is for constants that are declared both static and final.
Interfaces cannot be defined locally.
A local class, like a member class, cannot have the same name as any of its enclosing classes.
As noted earlier, a local class can use the local variables, method parameters, and even exception parameters that are in its scope, but only if those variables or parameters are declared final. This is because the lifetime of an instance of a local class can be much longer than the execution of the method in which the class is defined. For this reason, a local class must have a private internal copy of all local variables it uses (these copies are automatically generated by the compiler). The only way to ensure that the local variable and the private copy are always the same is to insist that the local variable is final.
So, as you can see, your first option (without nested methods) is preferable in these situations.
Quite simply - no. You can't nest a method within another method.
If you really want to do this, you can define classes within methods (strangely, given the previous restriction) and so could wrap your methods within a class within the outer method.
However, this isn't very idiomatic, and the general practice seems to be to have a list of private methods (in the top level class), perhaps grouped according to purpose and with comment blocks demarcating the groups.
If you happen to find yourself using Scala, however, you can nest methods away to your heart's content...
you can try in this way as well which is anonymous inner class.
public class SubFunction {
private String drawTribleX() {
// *** move trible(t) inside drawTribleX() ***
Trible t = new Trible() {
public String trible(String t) {
return t + t + t;
}
};
return t.trible("X");
}
public static void main(String[] args) {
SubFunction o = new SubFunction();
System.out.println(o.drawTribleX());
}
interface Trible {
String trible(String t);
}
}
You could use an anonymous class. Something like this;
class SubFunction {
public static void main(String[] args) {
SubFunction o = new SubFunction();
System.out.println(o.drawTribleX());
}
private String drawTribleX() {
MyTrible trible = new MyTrible() {
#Override
public String doTrible(String t) {
return t + t + t;
}
};
return trible.doTrible("X");
}
private interface MyTrible {
public String doTrible(String t);
}
}
If you wanted you could define different types of operations with the same interface, and pass these around as you like.
It is possible to write lambdas inside any method.
Using lambda for example to create a recursive method:
Expecting an object like
class Foo{
Foo parent;
}
Interface for the lambda method expression
public interface Function<ARGUMENTTYPE, RETURNTYPE>{
RETURNTYPE apply(ARGUMENTTYPE argument);
}
Recursive findRoot method to get the top level Foo.parent
private Foo findRoot(final Foo foo) {
//Create a Lambda Function for recursive search.
final Function<Foo, Foo> recursiveSearch = new Function<Foo, Foo>() {
#Override
public Foo apply(final Foo fee) {
//is the parent null return null
if (fee.parent == null) {
return null;
} else if (fee.parent.equals(fee)) {
//safety check ;-)
throw new IllegalStateException("Circular Dependencies of " + fee.toString());
} else {
Foo parentFoo = fee.parent;
//check if parent has parent otherwise return parent in else block
if (parentFoo != null && parentFoo.parent != null) {
return this.apply(parentFoo);
} else {
return parentMarket;
}
}
}
};
//get the root
final Foo rootFoo = recursiveSearch.apply(foo);
//Safety check 2 ;-)
if (rootFoo != null && rootFoo.equals(foo)) {
throw new IllegalStateException("Circular Dependencies of " + foo.toString)();
}
return rootFoo;
}
Related
I am a beginner and i try to teach myself clean coding. I want to pass a function as a parameter that I can reuse a method without to repeat code. As an example I have this:
public class Dog {
private String name;
private int id;
private List<String> characteristic;
public List<String> getCharacteristic() {
return characteristic;
}
public void setCharacteristic(List<String> characteristic) {
this.characteristic = characteristic;
}
}
public class Check{
private List<Dog> dogs = new ArrayList();
public void iterate() {
while (dogs.size() > 0) {
for (Dog dog : dogs) {
List<String> restChara = new ArrayList<>();
restChara= checkChara(dog, restChara);
if (restChara.size()>0) {
dog.setCharacteristic(restChara);
} else {
dogs.remove(dog);
}
}
}
}
private List<String> checkChara(Dog dog, List<String> restChara) {
for (String chara : dog.getCharacteristic()) {
boolean charaChecked = doSomething(chara);
if (!charaChecked) {
restChara.add(chara);
} else {
dog.getCharacteristic().remove(chara);
}
}
return restChara;
}
private boolean doSomething(String chara){
//do sth.
return true;
}
private boolean doSomething2(String chara){
//do sth.
return true;
}
}
How would you define the method checkChara in order to use different functions within it?
My first thought was to pass the function as a parameter (i think it would be in C# delegates)
Thank you very much!
EDIT:
I think I found another pattern strategy design pattern
https://www.freecodecamp.org/news/the-strategy-pattern-explained-using-java-bc30542204e0/
Java does not support “directly” nested methods. Many functional programming languages support method within method. But you can achieve nested method functionality in Java 7 or older version by define local classes, class within method so this does compile. And in java 8 and newer version you achieve it by lambda expression.
Method 1 (Using anonymous subclasses)
It is an inner class without a name and for which only a single object is created. An anonymous inner class can be useful when making an instance of an object with certain “extras” such as overloading methods of a class or interface, without having to actually subclass a class.
//Java program implements method inside method
public class GFG {
// create a local interface with one abstract
// method run()
interface myInterface {
void run();
}
// function have implements another function run()
static void Foo()
{
// implement run method inside Foo() function
myInterface r = new myInterface() {
public void run()
{
System.out.println("geeksforgeeks");
};
};
r.run();
}
public static void main(String[] args)
{
Foo();
}
}
Method 2 (Using local classes)
You can also implement a method inside a local class. A class created inside a method is called local inner class. If you want to invoke the methods of local inner class, you must instantiate this class inside method.
// Java program implements method inside method
public class GFG {
// function have implementation of another
// function inside local class
static void Foo()
{
// local class
class Local {
void fun()
{
System.out.println("geeksforgeeks");
}
}
new Local().fun();
}
public static void main(String[] args)
{
Foo();
}
}
Method 3 (Using a lambda expression)
Lambda expressions basically express instances of functional interfaces (An interface with single abstract method is called functional interface. An example is java.lang.Runnable). lambda expressions implement the only abstract function and therefore implement functional interfaces.
// Java program implements method inside method
public class GFG {
interface myInterface {
void run();
}
// function have implements another function
// run() using Lambda expression
static void Foo()
{
// Lambda expression
myInterface r = () ->
{
System.out.println("geeksforgeeks");
};
r.run();
}
public static void main(String[] args)
{
Foo();
}
}
I don't exaclty know what you mean, but i figure out it could be something like that:
List<Runnable> runMyStuff = new ArrayList<Runnable>();
String variable= "Hallo"; //needs to be effectively final
runMyStuff.add(() -> {
System.out.println(variable);
doSomething(variable);
});
runMyStuff.add(() ->{
System.out.println("This is a test");
});
runMyStuff.add(() ->{
System.out.println("2 + 2 = " + (2+2) );
});
runMyStuff.get(0).run();
runMyStuff.get(2).run();
runMyStuff.get(0).run();
runMyStuff.get(1).run();
runMyStuff.get(2).run();
will result in :
Hallo
2 + 2 = 4
Hallo
This is a test
2 + 2 = 4
When you put variables or Passing Parameters in those runnable methods, they need to be effectively final or you pass them in a container.
You can re-run each method.
And within those Methods you can execute other methods.
NOTE:
If you want to have return Parameters you could do the same with Callable and than ".call()" instead of run.
EDIT:
Under the assumption you mean character Check or something like that
Example for charaCheck passable Method With Interface:
public interface CharacterChecker{
//is a template returns boolean, need a String param
public boolean call(String chara);
}
A method that executes a passes method of the type of "CHaracterChecker"
public static void excecutePassedMethod(CharacterChecker checker, String chara) {
System.out.println(chara + ": " + checker.call(chara));
}
Two different implementations of a "Character Checker"
CharacterChecker goodChecker = new CharacterChecker() {
#Override
public boolean call(String chara) {
return "good".equals(chara);
}
};
CharacterChecker lazyCheker = new CharacterChecker() {
#Override
public boolean call(String chara) {
return "lazy".equals(chara);
}
};
The Methods that are Passed the "method" (More like anonymos class object with the method)
excecutePassedMethod(goodChecker, "bad");
excecutePassedMethod(goodChecker, "good");
excecutePassedMethod(goodChecker, "jolly");
excecutePassedMethod(lazyCheker, "frisky");
excecutePassedMethod(lazyCheker, "lazy");
result will be:
bad: false
good: true
jolly: false
frisky: false
lazy: true
In general - equivalent of final field in Java is the readonly field in C#. But the more I read about C# the more I see that there are some differences in details.
I've found myself two differences:
Fields marked as readonly assigned as part of definition can be reasigned in constructor
In Java it is not possible to do that with final fields. Examples:
Example - C Sharp
public class Foo
{
public readonly int a = 1;
public Foo()
{
a = 2;
}
}
and now
Foo f = new Foo();
Console.WriteLine(f.a);
will give us 2 as an output
(side question - is this behavior can be actualy used for something useful? As far as I know I cannot assign value to base class' readonly field in dervied class)
Example - Java
class Foo {
private final int i = 3;
public Foo() {
// compilation error
// i = 2;
}
}
Orders of initalization of readonly and final fields in class hierarchy are different in both languages
In Java it will go from base class to dervied.
In C# it will go from derived class to base.
Example - C Sharp
Based on article Eric Lippert: Why Do Initializers Run In The Opposite Order As Constructors? Part One:
public class Print
{
public Print(string text)
{
Console.WriteLine(text);
}
}
public class Base
{
private readonly Print #base = new Print("Base class");
}
public class Derived : Base
{
private readonly Print derived = new Print("Derived class");
}
In case of calling new Derived() we will see:
Derived class
Base class
As far as I understood - this order of initalization guarantees that readonly fields are always initalized before usage. In case of following code (based on second part of Eric's article - Why Do Initializers Run In The Opposite Order As Constructors? Part Two):
public class Foo
{
}
public class Base
{
public Base()
{
if (this is Derived)
{
((Derived)this).danger();
}
}
}
public class Derived : Base
{
private readonly Foo derived = new Foo();
public void danger()
{
Console.WriteLine("access: {0}", derived.GetHashCode());
}
}
Calling new Derived() is safe.
Example - Java
Similar code in Java:
class Print {
public Print(String text) {
System.out.println(text);
}
}
class Base {
private final Print base = new Print("Base class");
}
class Derived extends Base {
private final Print derived = new Print("Derived class");
}
Call new Derived() will result with:
Base class
Derived class
So in case of following code:
class Base {
public Base() {
if (this instanceof Derived) {
((Derived)this).danger();
}
}
}
class Derived extends Base {
private final Foo field = new Foo();
public void danger()
{
System.out.println("access: " + field.hashCode());
}
}
The call new Derived() will result with NullPointerException
Question
My question is: Are there other differences (even small ones) between Java's final fields and readonly fields in C# ? To make question more clear - I have in mind only final instance fields in Java (so no static finals, no final variables, no other final "thigs")
I was wondering, what if I have the following case:
public class MyObject<T> {
private T myTObject;
public void setMyTObject(T m) {
myTObject = m;
}
public T getMyTObject() {
return myTObject;
}
}
And now I want that class to react something like these:
MyObject<ObjectA> objA = new MyObject<ObjectA>();
ObjectA objAInstance = objA.getObjectA();
or
objA.setObjectA(otherObjectAInstance);
Is there a way to dynamically create methods based on T class name?
Or should I better extend ObjectA to MyObject and create those methods using super.get/seMyObject()?
For clarification:
The idea is to have a getter and setter method generated dynamically
so, if I create an instance of:
MyObject<A> objA = new MyObject<A>();
I would be able to call method:
objA.getA();
getA() will call internally getMyTObject() or just return myTObject
so MyObject may react based on T class and generate the corresponding method.
I have updated member attribute to differentiate from MyObject class, it may lead to confusion. also fixed Method return and parameter Type.
Update Answer is completely changed.
Sounds like you want to use something through reflection. The problem with truly dynamically generating the method names is that, as others have commented, it would have to be done in bytecode which means that other classes trying to use your dynamic classes don't have Java code to refer to. It can be done, but it would be a mess.
Instead, here's a possible solution using generics. Please note that this is something of a quick and dirty hack; I leave it to you to refine it. You define an interface with the getters and setters you want, with whatever you want them named:
package com.example.dcsohl;
public interface IntegerWrapper {
public Integer getInteger();
public void setInteger(Integer i);
}
And then, to use them, you use this class to do the heavy lifting. Note that the error checking isn't very good; for example, it doesn't check that "getFoo" at all corresponds to the name of the class being passed in; nor does it validate that the "foo" in "getFoo" matches the "setFoo" method. This is something you can improve on.
package com.example.dcsohl;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyWrapper<T> implements InvocationHandler {
Class<T> clazz = null;
T myvalue = null;
public static <W,T> W getInstance(Class<W> clazz, Class<T> clazz2) {
ProxyWrapper<T> wrapper = new ProxyWrapper<T>();
wrapper.setClass(clazz2);
#SuppressWarnings("unchecked")
W proxy = (W)Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] {clazz}, wrapper);
return proxy;
}
private void setClass(Class<T> clazz) {
this.clazz = clazz;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// getter has no arguments
if (method.getName().startsWith("get") && (args == null || args.length == 0)) {
return myvalue;
} else if (method.getName().startsWith("set") && args.length == 1) {
Object o = args[0];
if (o.getClass().isAssignableFrom(clazz)) {
#SuppressWarnings("unchecked")
T val = (T)o;
myvalue = val;
return null;
}
} else {
throw new Exception();
}
return null;
}
}
Finally, to use it, here's a quick sample:
package com.example.dcsohl;
public class Main {
public static void main(String[] args) {
Integer foo = 5;
IntegerWrapper wrapper = ProxyWrapper.getInstance(IntegerWrapper.class, Integer.class);
wrapper.setInteger(foo);
Integer bar = wrapper.getInteger();
System.out.println(bar);
}
}
It seems like a lot of work just to avoid writing simple wrapper classes, and you'd be right, but reflection has its uses, and this is something of a sampler.
This may seem a basic question, but I'd like to get this right.
I have a Class 'AWorld'. Within that class, I have a method that draws a border, depending on the map size set by the user.
If the variable 'mapSize' is private, but I want to access it's value from within the same class, is it more appropriate to reference it directly, or use a getter method.
The code below should explain what I'm wanting to know.
package javaFX;
public class AWorld {
//initialized later
AWorld newWorld;
private int mapSize = 20;
public int getMapSize()
{
return mapSize;
}
public void someMethod()
{
int var = newWorld.mapSize; //Do I reference 'mapSize' using this...
}
// Or...
public void someOtherMethod()
{
int var = newWorld.getMapSize(); //Or this?
}
public static void main(String[] args) {}
}
Either of those is ok since you're getting a primitive field. If the get method does another operation before returning the data e.g. performing a math operation on the value, then it would be better to use it rather than calling the field directly. This is specially meant when using proxy/decorator pattern on your classes.
Here's an example of the second statement from above:
//base class to be decorated
abstract class Foo {
private int x;
protected Foo foo;
public int getX() { return this.x; }
public void setX(int x) { this.x = x; }
public Foo getFoo() { return this.foo; }
//method to prove the difference between using getter and simple value
public final void printInternalX() {
if (foo != null) {
System.out.println(foo.x);
System.out.println(foo.getX());
}
}
}
//specific class implementation to be decorated
class Bar extends Foo {
#Override
public int getX() {
return super.getX() * 10;
}
}
//decorator
class Baz extends Foo {
public Baz(Foo foo) {
this.foo = foo;
}
}
public class Main {
public static void main(String[] args) {
Foo foo1 = new Bar();
foo1.setX(10);
Foo foo2 = new Bar(foo1);
//here you see the difference
foo2.printInternalX();
}
}
Output:
10
100
You better dereference it directly.
The point of the private modifier is not to expose internal implementation to other classes. These other classes will use the getter method to get the value of the private property.
In your own class, there is no point on using the getter. Worse, someone may have overridden that method in a class that extends your class, and the getter may perform something that you do not expect
IMHO, if you are referencing a field of the current instance the general rule is to access the field directly with mapSize or this.mapSize.
If you are referencing a value from a different instance (be it of the same class or a different class, I would use the getter method). I believe this would lead to simpler refactoring. It also maintains the contract that any other instance gets the field value via the getter which allows for additional functionality in the getter.
I have following classes (note that methods are static):
class Base
{
public static void whosYourDaddy()
{
Class callerClass = // what should I write here to get caller class?
System.out.print(callerClass.getName());
}
}
Class A extends Base
{
public static void foo()
{
A.whosYourDaddy();
}
}
Class B extends Base
{
public static void bar()
{
B.whosYourDaddy();
}
}
And when I call:
A.foo();
B.bar();
I'd like to get output:
AB instead of BaseBase. Is it even possible with static methods (in Java 7)?
What you can do, but shouldn't :) is use the Throwable getStackTrace method. Aside from the smell, this is pretty slow, because getting the stack trace isn't that fast. But you will get an array of StackTraceElement, and each one will contain the class of teh class that is calling it (and you can also get the file and line, and if you separate the two with a : you can get a clickable link in eclipse, not that I'd ever do such a thing...).
Something like
String className = new Throwable().getStackTrace()[1].getClassName();
Hope that helps :)
private static class Reflection {
private static final SecurityManager INSTANCE = new SecurityManager();
static Class getCallClass() {
return INSTANCE.getCallClass(2);
}
private Reflection() {
}
private static class SecurityManager extends java.lang.SecurityManager {
public Class getCallClass(int i) {
Class[] classContext = getClassContext();
if (i >= 0 && i + 1 < classContext.length) {
return classContext[i + 1];
}
return null;
}
};
}
Is it even possible with static methods (in Java 7)?
No, Static methods aren't inherited. Only non-static methods are inherited.
In your case change Base (and subclasses) as follows:
class Base
{
public void whosYourDaddy()
{
Class<?> callerClass = getClass();
System.out.print(callerClass.getName());
}
}