This question already has answers here:
My program keeps saying that the method cannot be resolved
(2 answers)
Closed 5 years ago.
My class Cupple needs to call the method beStored(char) of a class DataIterator that implements an interface StorableData.
Here the code of this interface StorableData :
package general_classes.cupples;
public interface StorableData {
public void beStored(char c);
}
Here the code of the implementation :
package general_classes.cupples;
public class Cupple<TYPE_OF_ELEMENTS> implements StorableData {
public void beStored(char c) {
}
}
And finally, here the code of the class DataIterator :
package general_classes.DataIteration;
public class DataIterator<StorableData> {
private StorableData root_storable_data;
public List<StorableData> iterate() {
this.root_storable_data.beStored(read_character);
}
}
Please note that I didn't write all the lines.
The problem is that the compiler tells me that he "cannot resolve the method beStored(int).
However, as you can see it, it's actually in the interface. So what's the problem ?
COMPLETE CODE.
INTERFACE :
package general_classes.cupples;
public interface StorableData {
public Cupple beStored(int c);
}
IMPLEMENTATION :
package general_classes.cupples;
import java.util.ArrayList;
public class Cupple<TYPE_OF_ELEMENTS> extends ArrayList<TYPE_OF_ELEMENTS> implements StorableData {
private int position_to_insert_element;
private int number_of_elements;
private Cupple<TYPE_OF_ELEMENTS> next_cupple;
private Cupple<TYPE_OF_ELEMENTS> current_empty_cupple;
public Cupple(int number_of_elements) {
this.position_to_insert_element = 0;
this.number_of_elements = number_of_elements;
}
public Cupple beStored(int c) {
Cupple returned_cupple = this;
if(this.position_to_insert_element > this.number_of_elements) {
this.next_cupple = returned_cupple = new Cupple<>(this.number_of_elements);
} else {
//this.add((TYPE_OF_ELEMENTS) c);
this.position_to_insert_element++;
}
return returned_cupple;
}
public Cupple next() {
return this.next_cupple;
}
}
CLASS :
package general_classes.DataIteration;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
/**
* Reads character per character some given data. Stores the character in a
* list, after having casted it in the specified type by the way.
*
* #author e1300478
*
* #param <StorableData>
* the wished type of the reading's returned elements
*/
public class DataIterator<StorableData> {
private Reader reader;
private List<StorableData> returned_elements_list;
private StorableData root_storable_data;
DataIterator(Reader reader, StorableData storable_data) {
this.reader = reader;
this.returned_elements_list = new ArrayList<>();
this.root_storable_data = storable_data;
}
public List<StorableData> iterate() throws IOException {
int read_character;
do {
read_character = this.reader.read();
StorableData storable_data = this.root_storable_data.beStored((int) read_character);
if(!this.returned_elements_list.contains(storable_data)) {
this.returned_elements_list.add(storable_data);
}
} while (read_character > -1);
return this.returned_elements_list;
}
}
The problem is that the compiler tells me that he "cannot resolve the
method beStored(int).
That simply means that you're attempting to pass an int type to the beStored method. If you look at the interface definition of this method again you'll notice that you're not obeying the contract that has been set.
public void beStored(char c);
in the code below read_character is most likely an int type rather than a character hence the error.
this.root_storable_data.beStored(read_character);
Solution
change this:
int read_character;
to this:
char read_character;
also change this:
StorableData storable_data = this.root_storable_data.beStored((int) read_character);
to this:
StorableData storable_data = this.root_storable_data.beStored(read_character);
The problem is this, in DataIterator StorableData is just a generic type, is not the class StorableData, is the same as DataIterator
The following code would compile.
public class DataIterator {
private StorableData root_storable_data;
public List<StorableData> iterate() {
char read_character='x';
this.root_storable_data.beStored(read_character);
return null;
}
}
Related
I have an object in use throughout my codebase, UnsecureObject. This object is auto-generated with no getters/setters, and all member fields are public. So editing is done by doing something like the following:
unsecureObjInstance.firstName = "Jane";
This is not desirable for numerous reasons that I probably don't have to explain here. But using this generated class is required for some other technical details with our messaging pipeline that I won't go into.
I have a desire is to leverage a mapping utility written by someone else on my team to convert this UnsecureObject to a pojo that I am writing.
An example of the mapper in action (with two normal classes w/ getters/setters) would be something like:
new MapperBuilder<>(PojoOne.class, PojoTwo.class)
.from(PojoOne::getName).to(PojoTwo::getFirstName)
.build();
This will map the PojoOne#name field to the PojoTwo#firstName field.
Is there a way to translate this to input my UnsecureObject here? I have tried something like the following:
new MapperBuilder<>(UnsecureObject.class, SecureObject.class)
.from(u -> u.firstName).to(SecureObject::getFirstName)
.build();
But get an error here, something along the lines of 'u -> u.firstName' could not be invoked.
So the question is:
Is there a way to essentially "construct" a getter on the fly using these public members? So in the .from() method, I can construct the call to look like a standard method that will yield my u.firstName?
Thanks for the help!
EDIT:
this is approx what the MapperBuilder class looks like (attempted to edit a bit to take away project specific wrappers/simplify)
/**
* This class is used to convert between POJO getter method references to the corresponding field names.
* #param <B> type
*/
public interface PojoProxy<B> {
/**
* Invokes the given getter method and returns information about the invocation.
* #param getter the getter to invoke
* #return information about the method invoked
*/
<T> GetterInvocation<T> invokeGetter(Function<B, T> getter);
}
/**
* Stores information about a method invocation.
* #param <T> method return type
*/
public interface GetterInvocation<T> {
public Class<T> getReturnType();
public String getFieldName();
}
/**
* A builder class to create {#link Mapper} instances.
* #param <FROM> source type
* #param <TO> target type
*/
public class MapperBuilder<FROM, TO> {
private final Class<FROM> _fromClass;
private final Class<TO> _toClass;
private final PojoProxy<FROM> _fromProxy;
private final PojoProxy<TO> _toProxy;
public MapperBuilder(Class<FROM> fromClass, Class<TO> toClass) {
_fromClass = fromClass;
_toClass = toClass;
//We will pretend there is an impl that provides the proxy.
//Proxies wrap the from and to classes in order to get reflection information about their getter calls.
_fromProxy = PojoProxy.of(fromClass);
_toProxy = PojoProxy.of(toClass);
}
public <FROM_VALUE> ToFieldBuilder<FROM_VALUE> from(Function<FROM, FROM_VALUE> getter) {
GetterInvocation<FROM_VALUE> methodInvocation = _fromProxy.invokeGetter(getter);
return new ToFieldBuilder<>(methodInvocation.getFieldName(), methodInvocation.getReturnType());
}
public class ToFieldBuilder<FROM_VALUE> {
private final String _fromFieldPath;
private final Class<FROM_VALUE> _fromClass;
public ToFieldBuilder(String fromFieldPath, Class<FROM_VALUE> fromClass) {
_fromFieldPath = fromFieldPath;
_fromClass = fromClass;
}
public <TO_VALUE> FromFieldBuilder<FROM_VALUE, TO_VALUE> to(Function<TO, TO_VALUE> getter) {
//similar to above, but now using a FromFieldBuilder.
}
}
public class FromFieldBuilder<FROM_VALUE, TO_VALUE> {
//impl..
}
}
I dont see MapperBuilder.from() method details, you can try this implementation of MapperBuilder.java Function (getter) -> (BiConsumer) setter
public class MapperBuilder<S, D> {
private final S src;
private final D dest;
public MapperBuilder(S src, Class<D> dest) {
this.src = src;
try {
this.dest = dest.newInstance();
} catch (Exception e) {
throw new RuntimeException("Required default constructor for: " + dest);
}
}
//getter - function to get value from source instance
//setter - biConsumer to set value to destination instance
//example - map(SrcClass::getSrcValue, DestClass::setDestValue)
public <V> MapperBuilder<S, D> map(Function<S, V> getter, BiConsumer<D, V> setter) {
setter.accept(dest, getter.apply(src));
return this;
}
public D build() {
return dest;
}
}
SrcClass.java some source class:
public class SrcClass {
private String srcValue;
public String getSrcValue() {
return srcValue;
}
public void setSrcValue(String srcValue) {
this.srcValue = srcValue;
}
}
DestClass.java some destination class:
package com.example.demo;
public class DestClass {
private String destValue;
public String getDestValue() {
return destValue;
}
public void setDestValue(String destValue) {
this.destValue = destValue;
}
}
DemoApplication.java demo:
public class DemoApplication {
public static void main(String[] args) {
SrcClass src = new SrcClass();
src.setSrcValue("someValue");
DestClass dest = new MapperBuilder<>(src, DestClass.class)
.map(SrcClass::getSrcValue, DestClass::setDestValue)
// map another fields
.build();
// for your UnsecureObject case
UnsecureObject unsecureObject = new MapperBuilder<>(src, UnsecureObject.class)
.map(SrcClass::getSrcValue,
(unsecure, srcValue) -> unsecure.unsecureValue = srcValue)
.build();
}
}
I have a class which have util functions and can be invoked on demand.
Steps to Reproduce :
TestMainWebApp (this project having Dependency of TestMainImp)
TestMainImpl ( this project implements TestMainInterface)
TestMainInterface
TestMainWebApp > TestMainServlet.java
package com.main;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.test.util.Util;
/**
* Servlet implementation class TestMainServlet
*/
#WebServlet("/TestMainServlet")
public class TestMainServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("\nCurrent ClassLoader chain: "+JavaEETrainingUtil.getCurrentClassloaderDetail());
Util prov = new Util();
// prov.test();
}
}
TestMainImpl > Util.java & TLSErrorRedirectListener.java
package com.test.util;
public class Util {
private final static String CLAZZ = Util.class.getName();
static {
System.out.println("Classloading of "+CLAZZ+" in progress..."+JavaEETrainingUtil.getCurrentClassloaderDetail());
}
public boolean checkForTLSErrorRedirection(boolean b) {
test.intf.ConfigurationListener listener = new com.listener.TLSErrorRedirectListener();
listener.valueChanged("test", "test");
return true;
}
public void test() {
System.out.println(" test util");
}
}
TLSErrorRedirectionListener.java
package com.listener;
import com.test.util.JavaEETrainingUtil;
public class TLSErrorRedirectListener implements test.intf.ConfigurationListener {
final static String CLAZZ = TLSErrorRedirectListener.class.getName();
static {
System.out.println("Classloading of "+CLAZZ+" in progress..."+JavaEETrainingUtil.getCurrentClassloaderDetail());
}
public void valueChanged(String key, String value) {
switch(key){
case "test1":
default : break;
}
}
}
TestMainInterface >ConfigurationListener.java
package test.intf;
public abstract interface ConfigurationListener
{
public abstract void valueChanged(String paramString1, String paramString2);
}
CASE :
TestMainInterface.jar will be in classpath of TestMainImpl.jar (#compiletime only)
At RunTime (i wont have TestMainInterface.jar) and I don't invoke the method "checkForTLSErrorRedirection()" . i invoke only test() method.
But Iam getting , java.lang.NoClassDefFoundError: test/intf/ConfigurationListener
when i create instance itself.
Can you please help to find out the root cause ? How does the java loads Class which is declared within a method ?
NOTE : JavaEETrainingUtil.java for debug purpose
package noclassdef.example1;
import java.util.Stack;
import java.lang.ClassLoader;
/**
* JavaEETrainingUtil
* #author Pierre-Hugues Charbonneau
*
*/
public class JavaEETrainingUtil {
/**
* getCurrentClassloaderDetail
* #return
*/
public static String getCurrentClassloaderDetail() {
StringBuffer classLoaderDetail = new StringBuffer();
Stack<ClassLoader> classLoaderStack = new Stack<ClassLoader>();
ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
classLoaderDetail.append("\n-----------------------------------------------------------------\n");
// Build a Stack of the current ClassLoader chain
while (currentClassLoader != null) {
classLoaderStack.push(currentClassLoader);
currentClassLoader = currentClassLoader.getParent();
}
// Print ClassLoader parent chain
while(classLoaderStack.size() > 0) {
ClassLoader classLoader = classLoaderStack.pop();
// Print current
classLoaderDetail.append(classLoader);
if (classLoaderStack.size() > 0) {
classLoaderDetail.append("\n--- delegation ---\n"); } else {
classLoaderDetail.append(" **Current ClassLoader**");
}
}
classLoaderDetail.append("\n-----\n");
return classLoaderDetail.toString();
}
}
This is not correct. You should not add the abstract keyword to interfaces or their methods. No need for public on interface methods; they are required to be public.
This is correct:
package test.intf;
public interface ConfigurationListener {
void valueChanged(String paramString1, String paramString2);
}
Be sure that the test.intf.ConfigurationListener.class file appears in your deployment. If it doesn't, the class loader will never find it.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
Please, help to understand what is wrong in next code, since I have pretty modest knowledge in Java generics.
Can't find out why I getting pageData is null in class BPage, when in APage it's fine. Thanks in advance.
I've simplified the excample classes to several rows:
public abstract class PageData {
}
public abstract class Page<T extends PageData> {
protected T pageData;
public Page(T pageData) {
this.pageData = pageData;
}
}
public class APageData extends PageData {
public final String locator = "//*[#id=\"id_1\"]";
}
public class APage<T extends APageData> extends Page<APageData> {
public APage(T pageData) {
super(pageData);
}
public void getLocator() {
System.out.println(pageData.locator);
}
}
public class BPageData extends APageData {
public final String locator = "//*[#class=\"class_1\"]";
}
public class BPage extends APage<BPageData> {
public BPage(BPageData pageData) {
super(pageData);
}
}
APage aPage = new APage(new APageData());
aPage.getLocator(); // locator found, OK
BPage bPage = new BPage(new BPageData());
bPage.getLocator(); //pageData NullPointerException
You need to tell the super what to do
public class BPage extends APage<BPageData> {
public BPage(BPageData pageData) {
super(pageData);
//this.pageData = pageData;
}
}
Im writing a mapreduce program where in reduce function receives as input value an iterable of PageRankNode(with two fields) object and im adding it to priority queue. On iterating over each object and adding it to priority queue, the resultant priority queue only contains the last object i added.
However, it seems to work as expected when i create a new object of the same type and add to priority queue.
I was wondering why is this happening?
Below sample works. However instead of "topPages.add(new PageRankNode(pageNode.pageName,pageNode.pageRank))", i use "topPages.add(pageNode)" it doesnt work as expected.
The comparator implementation for the priority queue is also added below.
private Comparator<PageRankNode> comparator= new PageNodeComparator();
private PriorityQueue<PageRankNode> topPages= new PriorityQueue<PageRankNode>(100,comparator);
public void reduce(NullWritable key,Iterable<PageRankNode> pageNodes,Context context) throws IOException,InterruptedException{
for(PageRankNode pageNode:pageNodes){
//topPages.add(pageNode);
topPages.add(new PageRankNode(pageNode.pageName,pageNode.pageRank));
if(topPages.size()>100){
topPages.poll();
}
}
PageRankNode pageNode;
while(!topPages.isEmpty()){
pageNode=topPages.poll();
context.write(NullWritable.get(),new Text(pageNode.pageName+":"+pageNode.pageRank));
}
}
public class PageNodeComparator implements Comparator<PageRankNode>{
public int compare(PageRankNode x,PageRankNode y){
if(x.pageRank < y.pageRank){
return -1;
}
if(x.pageRank > y.pageRank){
return 1;
}
return 0;
}
}
I don't think you provided enough information to properly diagnose this. I see that you have InterruptedException in the reduce method suggesting that you might be running this on multiple threads -- if so that might be the underlying cause.
I wrote a small program that does the same and its output is as expected.
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
public class Main {
private static Comparator<PageRankNode> comparator = new PageNodeComparator();
private static PriorityQueue<PageRankNode> topPages = new PriorityQueue<PageRankNode>(100, comparator);
public static void main(String[] args) {
reduce(Arrays.asList(
new PageRankNode("A", 1000),
new PageRankNode("B", 1500),
new PageRankNode("C", 500),
new PageRankNode("D", 700),
new PageRankNode("E", 7000),
new PageRankNode("F", 60)
));
}
public static void reduce(Iterable<PageRankNode> pageNodes) {
for(PageRankNode pageNode : pageNodes) {
//topPages.add(pageNode);
topPages.add(new PageRankNode(pageNode.pageName, pageNode.pageRank));
if(topPages.size() > 100) {
topPages.poll();
}
}
PageRankNode pageNode;
while(!topPages.isEmpty()) {
pageNode = topPages.poll();
System.out.println(pageNode.pageName);
}
}
public static class PageRankNode {
private String pageName;
private int pageRank;
public PageRankNode(String pageName, int pageRank) {
this.pageName = pageName;
this.pageRank = pageRank;
}
}
public static class PageNodeComparator implements Comparator<PageRankNode> {
#Override
public int compare(PageRankNode x, PageRankNode y) {
if(x.pageRank < y.pageRank) {
return -1;
}
if(x.pageRank > y.pageRank) {
return 1;
}
return 0;
}
}
}
Output is:
F
C
D
A
B
E
I am using BlazeDS to communicate between Java and Flash/Flex. And everything works fine, except that Java Null Integer becomes 0 on Flex side.
To handle the problem with transferring a Java Null Integer to an Flash/Flex int, I have implement a custom serialization, which works on the Java side and uses negative values to express Null values.
After implementing that I get an
RangeError: Error #2006: Der angegebene Index liegt außerhalb des zulässigen Bereichs.
(in english: the index is out of range)
at ObjectInput/readObject()
at mx.collections::ArrayList/readExternal()[E:\dev\4.x\frameworks\projects\framework\src\mx\collections\ArrayList.as:586]
at mx.collections::ArrayCollection/readExternal()[E:\dev\4.x\frameworks\projects\framework\src\mx\collections\ArrayCollection.as:147]
at ObjectInput/readObject()
at mx.messaging.messages::AbstractMessage/readExternal()[E:\dev\4.x\frameworks\projects\rpc\src\mx\messaging\messages\AbstractMessage.as:486]
at mx.messaging.messages::AsyncMessage/readExternal()[E:\dev\4.x\frameworks\projects\rpc\src\mx\messaging\messages\AsyncMessage.as:170]
at mx.messaging.messages::AcknowledgeMessage/readExternal()[E:\dev\4.x\frameworks\projects\rpc\src\mx\messaging\messages\AcknowledgeMessage.as:95]
The exception occures on the Flex side while deserializing the Java Result.
Which is an list of complex objects which contains this special class with the custom serialization. Because there was no such problem until I added the custom serialization, I guess it must belong to the problem, but i have no clue what triggers the exception.
This is the code of the object with the custom serialization:
package crux.domain.dto;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Serializable;
public class NullAbleID implements Serializable, Externalizable {
private static final long serialVersionUID = 788620879056753289L;
private Integer id;
public NullAbleID() {
super();
this.id = null;
}
public NullAbleID(final Integer id) {
this.id = id;
}
getter, setter for ID and hashCode and equals
#Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(this.nullToNegative(this.id));
}
#Override
public void readExternal(ObjectInput in) throws IOException {
this.id = this.negativeToNull(in.readInt());
}
private int nullToNegative(Integer id) {
if (id == null) {
return -1;
} else {
return id.intValue();
}
}
private Integer negativeToNull(int flashId) {
if (flashId < 0) {
return null;
} else {
return Integer.valueOf(flashId);
}
}
}
Flex: two classes, because we use Gas3 Granite Data Service code generation:
/**
* Generated by Gas3 v2.1.0 (Granite Data Services).
*
*/
package crux.domain.dto {
import flash.utils.IExternalizable;
[Bindable]
public class NullAbleIDBase {
public function NullAbleIDBase() {}
private var _id:Number;
public function set id(value:Number):void {
_id = value;
}
public function get id():Number {
return _id;
}
}
}
Flex sub class with read and write external
package crux.domain.dto {
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
import flash.utils.IExternalizable;
[Bindable]
[RemoteClass(alias="crux.domain.dto.NullAbleID")]
public class NullAbleID extends NullAbleIDBase implements IExternalizable{
public function readExternal(input:IDataInput):void {
id = input.readInt();
}
public function writeExternal(output:IDataOutput):void {
output.writeInt(id);
}
}
}
I have spend several hours on this problem, but I have no idea what the problem is.
Do you see the cause for the exception?
Not sure it's the cause of the problem, because I don't know BlazeDS, but the methods readExternal and writeExternal of your NullAbleID class are not symetric : you write an object of type Integer in writeExternal, and you read an int in readExternal.