Java, Object-independent null return - java

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;
}
}

Related

How can I return the right data type of a instance when this instance might have different data type?

I have this code in Modula-2,
PROCEDURE Prune(typeExp: TypeExp): TypeExp;
BEGIN
CASE typeExp.^class OF
| VarType:
IF typeExp^.instance = NIL THEN
RETURN typeExp;
ELSE
typeExp^.instance = Prune(typeExp^.instance);
RETURN typeExp^.instance;
END;
| OperType: RETURN typeExp;
END;
END Prune;
I have several problems when I try to convert this code into java. I can create an instance and judge if its instance is null and then choose what to return. But I don't really know what to do with the case 2, which is the instance might be a new Opentype(); because only one value can be returned in this case.
public TypeExp Prune(TypeExp typeExp){
TypeExp r = new VarType();
if (r.instance == null) {
return r;
}
else {
r.instance = Prune(r.instance);
return r.instance;
}
}
The second issue is I don't think I can call the function Prune() inside itself, so what can I do? Thanks in advance.
I dont really know Modula-2, but it might be something like this:
public TypeExp Prune(TypeExp typeExp) {
if (typeExp instanceof VarType) {
if (typeExp.instance == null) {
return typeExp;
}
else {
typeExp.instance = Prune(typeExp.instance);
return typeExp.instance;
}
} else if (typeExp instanceof OperType) {
return typeExp;
}
//if typeExp is not an instance of VarType or OperType
return null;
}
The Modula code does not return in all code paths. Thats not possible in Java. I inserted return null in those cases. Thats probably wrong for your application though.
Below example not same as your func, but I think you can modify to your needs. It hides your return types behind Type class => you can return objects of two classes.
Main
package com.type;
public class Main {
public static void main(String[] args) {
Type first = new FirstType();
Type second = new SecondType();
System.out.println(func(first).getTypeName());
System.out.println(func(first).getTypeName());
System.out.println(func(second).getTypeName());
}
public static Type func(Type type) {
if(type instanceof FirstType) {
type.setTypeName("First");
} else {
type.setTypeName("Second");
// something here
}
return type;
}
}
Type
package com.type;
public class Type {
private String typeName;
public Type() {}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
}
FirstType
package com.type;
public class FirstType extends Type {
}
SecondType
package com.type;
public class SecondType extends Type {
}

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();
}
}

Test if class's generic parameter is itself the same class with its own generic parameter

I'm not sure I've phrased the title correctly, but hopefully my pseudo code is nearly self explanatory. I don't know how to test if a SomeType object is an instance of MyClass (or a descendent). How could this be achieved?
public class MyClass<SomeType>
{
//...
public void a(SomeType st)
{
if (SomeType extendsOrIs MyClass<?>) // Need help with this line
{
MyClass<?> mc = (MyClass<?>) st;
mc.b();
}
}
public void b()
{
//...
}
}
One solution I've found is to do this, but it's possible the object is null, in which case I'd still like to know if SomeType is equivalent to MyClass<?> for the sake of calling a method for future objects:
public void a(SomeType st)
{
if (st instanceof MyClass<?>)
{
MyClass<?> mc = (MyClass<?>) st;
mc.b();
}
}
First of null is not an instance of any class.You can create a final method in MyClass such as :-
public class MyClass<SomeType>
{
//...
public void a(SomeType st)
{
if (SomeType extendsOrIs MyClass<?>) // Need help with this line
{
MyClass<?> mc = (MyClass<?>) st;
mc.b();
}
}
public final boolean isSubClass()
{
if(this.getClass()!=MyClass.class){
return true;
}
return false;
}
public void a(SomeType st)
{
if (st instanceof MyClass<?>)
{
MyClass<?> mc = (MyClass<?>) st;
mc.isSubClass();
}
}

Delegating method calls using variable number of arguments

This question came up in the course of my work programming; it's become irrelevant to the current task, but I'm still curious if anyone has an answer.
In Java 1.5 and up you can have a method signature using a variable number of arguments, with an ellipsis syntax:
public void run(Foo... foos) {
if (foos != null) {
for (Foo foo: foos) { //converted from array notation using autoboxing
foo.bar();
}
}
}
Suppose I want to do some operation on each foo in the foos list, and then delegate this call to some field on my object, preserving the same API. How can I do it? What I want is this:
public void run(Foo... foos) {
MyFoo[] myFoos = null;
if (foos != null) {
myFoos = new MyFoo[foos.length];
for (int i = 0; i < foos.length; i++) {
myFoos[i] = wrap(foos[i]);
}
}
run(myFoos);
}
public void run(MyFoo... myFoos) {
if (myFoos!= null) {
for (MyFoo myFoo: myFoos) { //converted from array notation using autoboxing
myFoo.bar();
}
}
}
This doesn't compile. How can I accomplish this (passing a variable number of MyFoo's to the run(MyFoo...) method)?
Is this what you want?
public class VarArgsTest {
public static class Foo {}
public static class MyFoo extends Foo {
public MyFoo(Foo foo) {}
}
public static void func(Foo... foos) {
MyFoo [] myfoos = new MyFoo[foos.length];
int i=0;
for (Foo foo : foos) {
myfoos[i++] = new MyFoo(foo);
}
func(myfoos);
}
public static void func(MyFoo... myfoos) {
for (MyFoo m : myfoos) {
System.out.println(m);
}
}
public static void main(String [] args) throws Exception {
func(new Foo(), new Foo(), new Foo());
}
}
I tried it and did NOT get a compile error. What is the actual error you are seeing? Here is the code I used. Perhaps i did something different:
public class MultipleArgs {
public static void main(String [] args){
run(new Foo("foo1"), new Foo("foo2"), new Foo("foo3"));
}
public static void run(Foo... foos){
MyFoo[] myFoos = null;
if (foos != null) {
myFoos = new MyFoo[foos.length];
for (int i = 0; i < foos.length; i++) {
myFoos[i] = wrap(foos[i]);
}
}
run(myFoos);
}
public static void run(MyFoo... myFoos){
if (myFoos!= null) {
for (MyFoo myFoo: myFoos) {
myFoo.bar();
}
}
}
private static class Foo {
public final String s;
public Foo(String s){
this.s = s;
}
#Override
public String toString(){
return s;
}
}
private static class MyFoo{
private final String s;
public MyFoo(String s){
this.s = s;
}
public void bar(){
System.out.println(s);
}
#Override
public String toString(){
return s;
}
}
private static MyFoo wrap(Foo foo){
return new MyFoo(foo.s);
}
}
This doesn't answer your question; it's incidental, but you don't need the null test. Here's proof:
public class VarargsTest extends TestCase {
public void testVarargs() throws Exception {
assertEquals(0, fn());
}
private int fn(String...strings) {
return strings.length;
}
}
If the method is called without any arguments, the varargs list is an empty array, not null.
I think the actual solution to your question would be to rename the second function.
use java reflections.

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