using class as method in java - java

How do I use (if possible) a class as a method parameter in Java?
public class validators() {
public int minLength(int l) {
// do something
}
}
public class formField() {
public void addField(String field, validators val) {
//do something
}
}
I want to be able to do the following :
addField("username", new validators() {
minLength(6);
});
Is it possible?

If you want to pass the current instance, you can use this.

Though I am not sure what are you trying to achieve yet the following code will compile fine:
public class Validators {
public int minLength(int l) {
// do something
return 0;
}
}
And
public class FormField {
public void addField(String field, Validators val) {
//do something
}
}
And then we can use it as:
public static void main(String[] args) {
FormField ff = new FormField();
ff.addField("username", new Validators() {
int result = minLength(6);
});
}
And it is making use of anonymous derived class.

If you want to pass a class instance as a parameter and define some value it'll use, you have to make this variable as attribute of the class and set it via the constuctor, like:
public class Validators {
int l;
public Validators(int l) {
this.l = l;
}
public int minLength() {
// do something
//here you can use l variable
}
}
And
public class FormField {
public void addField(String field, Validators val) {
//do something
}
}
Then you can call it like:
addField("username", new Validators(6)) {
...
And may be you have to take a look at Java naming conventions

Related

Java, Object-independent null return

Given Java source code and a preprocessor (like C++), I would like to replace all mentions of null with a function that returns null. It finds a call to null and replaces it with the following function.
public static Object returnNull(){
return null;
}
This fails because there are varied classes and:
functionThatWantsCustomClass( returnNull() ); //Object cannot be converted to CustomClass
or
if( cc == returnNull() ) //Object cannot be converted to CustomClass
etc.
Easiest solution I can imagine is having to parametrize the preprocessor, although that would require going through every single null to add the parameter maually, eg: null/*CustomClass*/.
Another method is spending a lot of time writing a much better parser so it always knows the required class for a returnTypedNull() function.
Is there a way to get through this error with minimal modification/parsing?
Use generics:
public static <T> T returnNull() {
return (T) null;
}
Follow-up from comment
The following code is as close to comment as I can decipher, and it compiles fine:
public class Test {
public static void main(String[] args) {
CustomClass cc = new CustomClass();
if (cc != returnNull())
cc.errlog( returnNull() );
}
public static <T> T returnNull() {
return (T) null;
}
}
class CustomClass {
void errlog(Exception e) {
}
}
Now, if there are 2 errlog methods with only one non-primitive parameter:
class CustomClass {
void errlog(Exception e) {
}
void errlog(String s) {
}
}
Then it will fail with error The method errlog(Exception) is ambiguous for the type CustomClass, because the compiler doesn't know whether T should be Exception or String, i.e. which of the two to call.
You have to explicitly tell the compiler:
cc.errlog( Test.<Exception>returnNull() );
Use generics ant it will work.
Example:
public class ReturnNullExample {
public static void main(String[] args) {
ReturnNullExample example = new ReturnNullExample();
example.someMethod(ReturnNullClass.returnNull());
CustomClass cc = null;
if(cc == ReturnNullClass.returnNull()) {
System.out.println("cc is null");
}
cc = new CustomClass();
if(cc != ReturnNullClass.returnNull()) {
System.out.println("cc is not null");
}
}
public void someMethod(CustomClass customClass) {
System.out.println("This method does nothing");
}
}
class CustomClass {
private int number;
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}
class ReturnNullClass {
public static <T> T returnNull() {
return null;
}
}

How to pass a parameter in a fluent API before calling any function?

I have this kind of class
public class AImpl implements A {
private String variable = "init";
#Override
public A choice(A... choices) {
return this;
}
#Override
public A execute() {
variable = "execute";
return this;
}
}
I can use it like this (simple example)
new AImpl().choice(
new AImpl[] {
new AImpl().execute(),
new AImpl()
};
)
or like this (more complex example, with variable expected value)
new AImpl().choice( //variable == "init"
new AImpl[] {
new AImpl().execute(), //variable == "init". Set to "execute"
new AImpl().choice( //variable == "init"
new AImpl[] {
new AImpl() //variable == "init"
}
),
new AImpl().execute().choice( //variable == "init". Set to "execute"
new AImpl[] {
new AImpl(), //variable == "execute"
new AImpl() //variable == "execute"
}
),
};
)
What I'm trying to achieve
Each time there is a choice, I would like to propagate the last value of variable to each new instances. Here is graph version of the complex example where I encircled what I called propagation
What is my question
How can I propagate this variable to all the objects in the choices list before calling any other function (before calling execute in the simple example above, because this function uses (and can modify) this variable).
What I have tried
I can not do it using the constructor since I don't have a reference to the variable
public AImpl(String variable) {
this.variable = variable;
}
This code will not work because the variable will be set after all functions
#Override
public A choice(A... choices) {
for(A a : choices) {
a.setVariable(variable);
}
}
I tried with a Builder (eg set all the values and only create the instance at the end, from the choice function for example). But it make sense to chained the functions execute or choice (...execute().execute().choice()...). So the builder become difficult to create and can become really big.
I also tried to move the variable to a context class, but it is not working if in the choices I have another choice (case of the more complex example). Here is my current context class
public class Context {
private static Context instance = null;
private String variable;
private Context(){};
public String getVariable() {
return variable;
}
public void setVariable(String variable) {
this.variable = variable;
}
public static void set(String variable) {
if(Context.instance == null)
Context.instance = new Context();
Context.instance.setVariable(variable);
}
public static String get() {
if(Context.instance == null)
throw new NullPointerException();
return Context.instance.getVariable();
}
}
The problem is that new AImpl instances need to inherit the context of their "parent" AImple instance, i.e. the one on which choice() is called. You can't do that using the new operator. You should instead have a method that creates the instances with an inherited variable.
public A[] createChoices(int count, A optionalDefaultValues...) {
// return an array of clones of itself (possibly with adjusted defaults)
}
I finally found a working solution based on the Context approach (see What I have tried ?)
The main idea
There are two mains ideas. The first one is to replace (inside the context object) the single variable by a Stack of variables like this one
Stack<String> variables = new Stack<>();
I push the first variable in the first constructor and them I can access and modify it using pop/push function
String variable = Context.pop();
//Do something with variable
Context.push("anotherValue");
The second main idea is to duplicate the value on the top of the stack each time I create a new choice and to remove it at the end of each choice.
My code
Here is my code, if it can help someone else. I'm sure there is a lot of things to do to improve it, but it solved my original problem.
TestSo.java
public class TestSo {
#Test
public void testSo() {
AImpl.create().choice(
new ChoiceList()
.add(AChoice.create().execute())
.add(AChoice.create().choice(
new ChoiceList().add(AChoice.create())
))
.add(AChoice.create().execute().choice(
new ChoiceList()
.add(AChoice.create())
.add(AChoice.create())
))
);
}
}
A.java
public interface A {
A choice(ChoiceList choices);
A execute();
}
AAbstract.java
public class AAbstract implements A {
#Override
public A choice(ChoiceList choices) {
return this;
}
#Override
public A execute() {
String variable = Context.get();
//...
Context.set("execute");
return this;
}
}
AImpl.java
public class AImpl extends AAbstract {
private AImpl() {
Context.set("init");
}
public static AImpl create() {
return new AImpl();
}
}
AChoice.java
public class AChoice extends AAbstract {
private AChoice() {
Context.duplicate();
}
public static AChoice create() {
return new AChoice();
}
#Override
public AChoice choice(ChoiceList choices) {
super.choice(choices);
return this;
}
#Override
public AChoice execute() {
super.execute();
return this;
}
}
ChoiceList.java
public class ChoiceList {
private List<AChoice> choices = new ArrayList<>();
public ChoiceList add(AChoice choice) {
Context.remove();
choices.add(choice);
return this;
}
}
Context.java
public class Context {
private static Context instance = null;
private Stack<String> variables = new Stack<>();
private Context(){};
public String peek() {return variables.peek();}
public String pop() {return variables.pop();}
public void fork() {variables.push(variables.peek());}
public void push(String variable) {variables.push(variable);}
public static void set(String variable) {
if(Context.instance == null)
Context.instance = new Context();
Context.instance.push(variable);
}
public static String get() {
if(Context.instance == null)
throw new NullPointerException();
return Context.instance.pop();
}
public static void remove() {
if(Context.instance == null)
throw new NullPointerException();
Context.instance.pop();
}
public static void duplicate() {
if(Context.instance == null)
throw new NullPointerException();
Context.instance.fork();
}
public static String read() {
if(Context.instance == null)
throw new NullPointerException();
return Context.instance.peek();
}
}

How to get value of variable from other class?

I have a public integer variable (MainReg) in my Counter Class. I want to get value of this variable and set it in my JComponent class. Here is piece of my JComponent class:
public class Komponent2 extends JComponent implements ActionListener
{
Counter counter3;
.
.
.
int a = counter3.valueOf(MainReg);
But it doesn't work. I tried also:
int a = valueOf(counter3.MainReg);
int a = counter3.valueOf(counter3.MainReg);
int a = counter3.MainReg;
But it still doesn't work. How can I get this variable? Thanks for helping me.
EDIT
Here is my Counter class:
import java.util.Observable ;
public class Counter extends Observable
{
public int MainReg;
public int CompareReg;
public Mode countMode;
public boolean OVF;
private int a=0;
public Counter()
{
OVF=false;
}
public void setCompareReg(int dana)
{
CompareReg=dana;
}
public void setMainReg(int dana2)
{
MainReg=dana2;
}
public void setMode(Mode countMode)
{
this.countMode=countMode;
}
public void Count()
{
if (countMode==Mode.UP)
{
MainReg++;
OVF=false;
if (CompareReg < MainReg)
{
OVF=true;
MainReg=0;
setChanged();
notifyObservers();
}
}
else if (countMode==Mode.UPDOWN)
{
if(MainReg >= CompareReg)
{
a=MainReg;
MainReg--;
OVF=true;
}
else
{
if(MainReg >= a)
{
MainReg++;
OVF=false;
}
else
{
MainReg--;
if(MainReg==0)
{
a=0;
}
OVF=false;
}
}
}
else if (countMode==Mode.CONTINOUS)
{
MainReg++;
OVF=false;
if (65536 < MainReg)
{
MainReg=0;
OVF=true;
}
}
}
}
Well I see two ways you can do this.
Your MainReg integer is public, you could simply use int i = counter3.MainReg;
Or you could create a getMainReg() method in your Counter class. Then call it from whatever class.
EX:
public int getMainReg() {
return this.MainReg;
}
Give your Counter class getter methods, and then call them when you need to access their values. i.e.,
public int getMainReg() {
return mainReg;
}
public int getCompareReg(){
return compareReg;
}
public Mode getCountMode() {
return countMode;
}
And make your fields all private. Also your code should obey Java naming rules: variable names should begin with lower-case letters.
Also be sure that you've initialized your counter variable in the class that uses it, either by creating a new instance, or if appropriate, passing in a valid instance in a constructor or method parameter.

How can I get data of different types from an anonymous class

I have an object that delegates some work to another object which is implementing an interface. Then, I am creating anonymous classes implementing this interface and I would like to get information from these.
Is it okay to use a final array with a size of one as a pointer to a primitve to share data with the anonymous class?
Here is a working example of what I mean :
public class ExampleClass
{
public static final int INVALID_VALUE = -1;
public static void main(final String[] args)
{
final int[] buffer = { INVALID_VALUE }; // buffer is created
final InterfaceA iaObject = new InterfaceA()
{
#Override
public void doStuff(final String paramA)
{
buffer[0] = paramA.length(); // buffer is filled in anonymous class
}
};
final ClassA objA = new ClassA(iaObject);
objA.doStuff("hello, world");
if (buffer[0] == INVALID_VALUE) // buffer is used
{
System.err.println("Invalid length !");
}
else
{
System.err.println("The length is : " + Integer.toString(buffer[0]));
}
}
public static class ClassA
{
private final InterfaceA iaObject;
public ClassA(final InterfaceA iaObject)
{
this.iaObject = iaObject;
}
public void doStuff(final String paramA)
{
this.iaObject.doStuff(paramA);
}
}
public static interface InterfaceA
{
void doStuff(String paramA);
}
}
Thanks
Suggestion: why not using a generic for an out parameter?
interface InterfaceA {
public <T> void doStuff( String paramA, Holder<T> holder );
}
class Holder<T> {
public T t;
}
Full example:
public class ExampleClass
{
public static final int INVALID_VALUE = -1;
public static void main(final String[] args)
{
final InterfaceA< Integer > iaObject = new InterfaceA< Integer >() {
#Override
public Integer doStuff( String paramA, Holder<Integer> holder ) {
return holder.value = paramA.length();
}
};
final ClassA<Integer> objA = new ClassA<>( iaObject );
int result = objA.doStuff("hello, world", new Holder<>( INVALID_VALUE ));
if( result == INVALID_VALUE ) {
System.err.println("Invalid length !");
}
else {
System.err.println("The length is : " + Integer.toString( result ));
}
}
public static class ClassA<T> {
private final InterfaceA<T> iaObject;
public ClassA( final InterfaceA<T> iaObject_ ) {
this.iaObject = iaObject_;
}
public T doStuff( final String paramA, Holder<T> holder ) {
return this.iaObject.doStuff( paramA, holder );
}
}
public static interface InterfaceA<T> {
public T doStuff( String paramA, Holder<T> resultHolder );
}
public static class Holder<T> {
public T value;
public Holder( T value_ ) {
value = value_;
}
}
}
If I understand the gist of your question, you're wondering if it is good design principle to use a final array as a wrapper to share memory between an anonymous inner class and its enclosing class.
In my experience, this is a pretty poor way of sharing data between two objects. It is probably wiser to declare your interface differently. Either return an object or use a generic to specify what type you expect back from your anonymous class.
I think one of the largest problems with your approach is the lack of encapsulation - your InterfaceA implementation uses some "global" data holder (the array), and there is no way to prevent that this array can be used elsewhere, which in turn could lead to all kinds of problems (race conditions or whatever).
A cleaner way would be the definition of some separate class (or interface) with a getInt()-method or something similar.

tagging methods and calling them from a client object by tag

I have been trying to figure out a way to tag several methods from my base class, so that a client class can call them by tag. The example code is:
public class Base {
public void method1(){
..change state of base class
}
public void method2(){
..change state of base class
}
public void method3(){
..change state of base class
}
}
A client class from a main() method will call each method of Base through a random instruction sequence:
public static void main(String[] args) {
String sequence = "ABCAABBBABACCACC"
Base aBase = new Base();
for (int i = 0; i < sequence.length(); i++){
char temp = sequence.charAt(i);
switch(temp){
case 'A':{aBase.method1(); break;}
case 'B':{aBase.method2(); break;}
case 'C':{aBase.method3(); break;} }
}
System.out.println(aBase.getState());
}
Now I wish to get rid of the switch statement altogether from the Client object. I am aware of the technique to replace switch by polymorphism, but would like to avoid creating a set of new classes. I was hoping to simply store those methods in an appropriate data structure and somehow tag them with a matching character from the sequence.
A map could easily store objects with value/key pairs which could do the job, (as I did here), or the command pattern, but since I don't want to replace those methods with objects, is there a different way perhaps, to store methods and have a client selectively call them?
Any advice is appreciated
Something like this?
public class Base {
private final Map<Character, Method> methods = new HashMap<Character, Method>();
public Base() throws SecurityException, NoSuchMethodException {
methods.put('A', getClass().getMethod("method1"));
methods.put('B', getClass().getMethod("method2"));
methods.put('C', getClass().getMethod("method3"));
}
public Method getMethod(char c) {
return methods.get(c);
}
public void method1() {}
public void method2() {}
public void method3() {}
}
and then
public static void main(String[] args) throws Exception {
String sequence = "ABCAABBBABACCACC";
Base aBase = new Base();
for (int i = 0; i < sequence.length(); i++) {
char temp = sequence.charAt(i);
aBase.getMethod(temp).invoke(aBase);
}
}
I would use annotations on the methods in question, allowing it to be marked as a "tagged method", and providing the tag string to use for that method.
From that point the implementation gets simpler; you can use reflection to iterate over a class' methods and inspect their annotations; perhaps do this statically at startup and populate a mapping from tag string to java.lang.reflect.Method.
Then when processing the command string, invoke the methods that correspond to each tag.
Edit: some example code:
import java.lang.annotation.*;
#Retention(RetentionPolicy.RUNTIME)
#interface TaggedMethod {
String tag();
}
Then in the base class:
public class Base {
#TaggedMethod(tag = "A")
public void method1(){
..change state of base class
}
#TaggedMethod(tag = "B")
public void method2(){
..change state of base class
}
#TaggedMethod(tag = "C")
public void method3(){
..change state of base class
}
}
...and in the client:
private static final Map<String, Method> taggedMethods = new HashMap<String, Method>();
// Set up the tag mapping
static
{
for (Method m : Base.class.getDeclaredMethods())
{
TaggedMethod annotation = m.getAnnotation(TaggedMethod.class)
if (annotation != null)
{
taggedMethods.put(annotation.tag(), m);
}
}
}
so that you can access this as:
public static void main(String[] args) throws Exception
{
String sequence = "ABCAABBBABACCACC"
Base aBase = new Base();
for (int i = 0; i < sequence.length(); i++)
{
String temp = sequence.substring(i,1);
Method method = taggedMethods.get(temp);
if (method != null)
{
// Error handling of invocation exceptions not included
method.invoke(aBase);
}
else
{
// Unrecognised tag - handle however
}
}
System.out.println(aBase.getState());
}
This code hasn't been compiled or tested, by the way... :-)
You could use Attributes for this, in C#. For Java, use annotations. Derive a class from the Attribute class, say, TagAttribute, and apply the attribute to the methods.
[global::System.AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public sealed class TagAttribute : Attribute
{
public TagAttribute(char value)
{
this.value = value;
}
private char value;
public char Value
{
get { return value; }
}
}
Apply the attribute to the methods:
public class MyClass
{
[Tag('A')]
public void Method1()
{ Console.Write("a"); }
[Tag('B')]
public void Method2()
{ Console.Write("b"); }
[Tag('C')]
public void Method3()
{ Console.Write("c"); }
}
Invoke the methods using reflection:
private static void CallTaggedMethod(MyClass instance, char value)
{
MethodInfo methodToCall = null;
// From the MyClass type...
Type t = typeof(MyClass);
// ...get all methods.
MethodInfo[] methods = t.GetMethods();
// For each method...
foreach (MethodInfo mi in methods)
{
// ...find all TagAttributes applied to it.
TagAttribute[] attributes = (TagAttribute[])mi.GetCustomAttributes(typeof(TagAttribute), true);
if (attributes.Length == 0)
// No attributes, continue.
continue;
// We assume that at most one attribute is applied to each method.
TagAttribute attr = attributes[0];
if (attr.Value == value)
{
// The values match, so we call this method.
methodToCall = mi;
break;
}
}
if (methodToCall == null)
throw new InvalidOperationException("No method to call.");
object result = methodToCall.Invoke(
// Instance object
instance,
// Arguments
new object[0]);
// 'result' now contains the return value.
// It is ignored here.
}
Call the CallTaggedMethod from your Main method:
static void Main(string[] args)
{
String sequence = "ABCAABBBABACCACC";
MyClass inst = new MyClass();
foreach(char c in sequence)
CallTaggedMethod(inst, c);
// The rest.
Console.ReadLine();
}
Here is my annotations Approach. You don't even need a Map of tags to methods if you are using annotations, just iterate over the sequence and lookup the method for that tag using reflection.
import java.lang.annotation.*;
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface Tag {
char value();
}
then:
public class Base {
StringBuilder state = new StringBuilder();
#Tag('A')
public void method1(){
state.append("1");
}
#Tag('B')
public void method2(){
state.append("2");
}
#Tag('C')
public void method3(){
state.append("3");
}
public String getState() {
return state.toString();
}
}
then
public final class TagRunner {
private TagRunner() {
super();
}
public static void main(String[] args) throws IllegalArgumentException,
IllegalAccessException, InvocationTargetException {
Base b = new Base();
run(b, "ABCAABBBABACCACC");
System.out.println(b.getState());
}
private static <T> void run(T type, String sequence) throws
IllegalArgumentException, IllegalAccessException, InvocationTargetException {
CharacterIterator it = new StringCharacterIterator(sequence);
Class<?> taggedClass = type.getClass();
for (char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {
getMethodForCharacter(taggedClass, c).invoke(type);
}
}
private static Method getMethodForCharacter(Class<?> taggedClass, char c) {
for (Method m : taggedClass.getDeclaredMethods()) {
if (m.isAnnotationPresent(Tag.class)){
char value = m.getAnnotation(Tag.class).value();
if (c == value) {
return m;
}
}
}
//If we get here, there are no methods tagged with this character
return null;
}
}

Categories